Question

I am writing code for a program I am creating, and all I want this part of my code to do is ask the user to input a number.

import java.util.Scanner;

public class DiceRoller {       


    System.out.println("Please input a number of you choice"); 

    Scanner x = new Scanner(System.in);

    double repeats = x.nextInt(); 

    if(x.hasNextInt()){            
        repeats = (int)Math.round(repeats);


    }          

}

So this asks me for a number, but I will have to input twice.

It also only uses the first input as the variable

Was it helpful?

Solution

After you got a nextInt(), you asked it if it had another input with hasNextInt() it only knows this if you enter something more.

Perhaps you intended to put nextInt() inside the if block. Perhaps you also want to use int repeats as its an int value.

OTHER TIPS

You are calling x.hasNextInt() and the Scanner waits for another input to check if it is an int. You are also reading in an int and assigning it to a double (which an int is not). And to further it, you pass your int/double hybrid to Math.round which converts it to a Long and then casts it to an int and tries to assign it to a double.

If you are wanting to check if an a line is an int, you should try something like:

System.out.println("Please enter an integer.");
String line = x.nextLine();
int res=0;
try{
   res=Integer.parseInt(line);
}catch(Exception e){
   System.out.println("Not a number");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top