Sunday, 29 November 2015
Recursive Factorial in Java
public class RecursiveFactorial {
public static void main(String[] args) {
System.out.println(""+factorial(5));
}
public static long factorial(long x) {
if (x == 1) return 1;
else return x * factorial(x-1);
}
}
Output :
120
Labels:
args,
factorial,
FactorialDemo,
if,
if else,
java,
java examples,
main,
public,
recursive,
recursive factorial,
recursive function,
return,
static,
String,
String[],
System,
System.out.println(),
void
Factorial in Java
public class FactorialDemo {
public static void main(String[] args) {
System.out.println(""+factorial(5));
}
public static int factorial(int x) {
int fact = 1;
for(int i = 2; i <= x; i++) {
fact *= i;
}
return fact;
}
}
Output :
120
Friday, 27 November 2015
Reading Input from Command Line using Stream Class
class JStreamDemo
{
public static void main(String[] args)
{
String text = null;
InputStreamReader inputStream = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStream);
text = bufferedReader.readLine();
System.out.println(text);
}
}
Given Input :
Java is programming language.
Output :
Java is programming language.
Labels:
args,
Buffered,
BufferedReader,
bufferedReader.readLine(),
class,
import,
in,
input,
InputStreamReader,
io,
java,
main,
public,
Reader,
readLine(),
String,
System,
System.out.print(),
System.out.println()
Reading Input from Command Line
Below will explain how to get the input string from commandline:
public class JScanDemo
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
String name = scanner.next();
System.out.println(name);
}
}
Given Input :
---------------
Enter name:
Rajesh
Output :
----------
Rajesh
Labels:
{,
},
args,
class,
in,
io,
java,
java io,
main,
name,
public,
scanner,
scanner.next(),
static,
String,
System,
System.out.print(),
System.out.println(),
void
Subscribe to:
Posts (Atom)