So I'm trying to make a program where the user inputs a number and the computer outputs the factorial. I have to use recursion and have 1 class and 1 client.
My class is:
public class Factorial
{
public static int Factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*(Factorial(n-1));
}
}
}
My client is:
public class FactorialClient
{
public static void main()
{
Factorial n = new Factorial();
System.out.println(n.Factorial(4));
}
}
These both compile and work completely fine. However, I'm trying to figure out a way for the user to input the number instead of my inputting the number inside the client. Please help!
Try this.
public class FactorialClient
{
public static void main()
{
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int x = reader.nextInt();
Factorial n = new Factorial();
System.out.println(n.Factorial(x));
}
}
The Scanner class is great for reading user input.
The following should work:
public class FactorialClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();
System.out.println(Factorial.Factorial(userInput));
}
}
Note that you don't have to declare a new Factorial object because the Factorial method has been declared static.
Related
How do I make this program run until the user enters a specific key, lets say x, to terminate the program?
public class NestedLoopTableApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Table Numbers [one at a time]");
int valueOne = sc.nextInt();
int valueTwo = sc.nextInt();
NestedLoopTable np = new NestedLoopTable(valueOne, valueTwo);
np.printTable();
sc.close();
}
}
Just add your code block into the while loop and add a condition
while(sc.nextLine().equals("x")) {
//...... your code here
}
Thanks,
Vijay Kareliya
I'm not allowed to use any loops in my assignments lately, which has me stumped on this latest assignment. I'm supposed to ask the user for a series of integers, indefinitely, until they enter a non-integer, then inform them of the greatest integer. This following code, however, only takes in a single input:
public class GreatestNumber {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int a;
int g=0;
System.out.println("Enter several numbers. Enter a non-integer to end.");
if(in.hasNext()){
try{a=in.nextInt();
g=Greatest(a); }
catch (NumberFormatException e){
System.out.println("Greatest number in that sequence is "+g);
}}}
public static int Greatest(int x){
int g=0;
if (x>g){
g=x;
}
return g;
}
}
That is a lot of code. You could use recursion. Define greatest as taking a Scanner, check for an int and recurse with Math.max(int, int). Like,
public static int greatest(Scanner in) {
if (in.hasNextInt()) {
return Math.max(in.nextInt(), greatest(in));
}
return Integer.MIN_VALUE;
}
Then to call it, you only need something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter several numbers. Enter a non-integer to end.");
System.out.println("Greatest number in that sequence is " + greatest(in));
}
So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
probably missing something really silly, but my while loop will not stop printing the error message.
Could someone have a quick look and point me in the right direction?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
This line is the problem
while (carryOn = true) {
Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes
while (true) {
Just change that problem line to
while (carryOn == true) {
Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
In your case:
while(carryOn==true)
or
while(carryOn)
will solve your problem
import java.util.Scanner;
public class CHP4Ex
{
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
Why am I getting this error? I'm basically writing a while loop that prints all positive numbers that are divisible by 10 and less than n. For example, if n is 100, enter 10 ... 90.
Put the Scanner class object inside the main function. Basically the problem is that your code violates the static feature. You cannot use non-static members inside a static function, main being static in your case. So it should be :
import java.util.Scanner;
public class CHP4Ex
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
You can't refer to non static variable in static context, so change
Scanner scan = new Scanner(System.in);
to
private static Scanner scan = new Scanner(System.in); It should work