I am really new to Java, as well as programming. And I have been going at this problem for a while. It seems like a quick fix but I just couldn't find something similar online:
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.Scanner;
import javax.swing.plaf.synth.SynthScrollBarUI;
public class main {
public static void main(String[] args) {
int x;
int y;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your first number: ");
x = scan.nextInt();
if (scan.hasNextInt() == false) {
System.out.println("Thats not a number, please try again.");
}
System.out.println("Your first number is " x);
System.out.println("Enter your second number: ");
y = scan.nextInt();
if (scan.hasNextInt() == false) {
System.out.println("Thats not a number, please try again.");
}
System.out.println("Your numbers are " x " and " y);
}
}
I am trying to tell the code to ask the user to enter x and y using the same scanner, but when I try to run my code, my output tells me to enter the x twice instead of asking for the y right after my first x input. Even when I go through with the code, when It states the x and y, it only shows the first two numbers added and not my y.
I'm thinking it may be because I have entered my scanner into the loops wrong, since I told the code to only accept integers from the user.
Any help would be great, sorry if it wasn't the best explanation I am still new.
CodePudding user response:
Your current code is logically incorrect, first you get an int then you check if there is an int to get. You need something like
while (!scan.hasNextInt()) {
System.out.println("Thats not a number, please try again.");
scan.nextLine();
}
x = scan.nextInt();
System.out.println("Your first number is " x);
System.out.println("Enter your second number: ");
while (!scan.hasNextInt()) {
System.out.println("Thats not a number, please try again.");
scan.nextLine();
}
y = scan.nextInt();
System.out.println("Your numbers are " x " and " y);
CodePudding user response:
Your first if statement is asking if (scanner has a next int type token to read). Scanner.hasNext is a boolean to read if there is a next token to read. Here's the link for the Scanner class so you can get better informed on how the class work.https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html int variables are set to 0 by default. So if you're expecting a value bigger than zero from the user then I would check if your x is less or equal than 0 if(x <= 0) { print something} Or if you expect any value , then you can use the Integer instead of the primitive type int. Integer wrapper class that take int primitive and creates an object that is initialized null if no value was given when declared. So in your if statement you can if( x == null) { print something) Here's the link for that https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
