Question

Im trying to make a program that is a simple adder but I need it to be able to read an Integer or Enter. For example after the user enters the first value(a) the program would save that as a temp variable then when it prompts for the second input the user could either just hit enter and the program would just display the previous value(a) and use that as the second value.

example code

Scanner in = new Scanner(System.in);
System.out.println("Enter Value");
a = in.nextInt();
temp = a;
System.out.println("Enter Value");
// here you could hit enter or enter another value
if(user press enter)
b = temp;
else
b = in.nextInt();
temp = b;

a = a+b;
System.out.println(a);
Était-ce utile?

La solution

Well as a newline can not be converted to an int then nextInt just ain't going to work.

try using nextLine and then see if you can convert to an Integer to process or convert to newLine to quit.

see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

and

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

Autres conseils

Scanner in = new Scanner(System.in);
System.out.println("Enter Value");
a = in.nextInt();
temp = a;
System.out.println("Enter Value");
// here you could hit enter or enter another value
int b = in.nextInt();
if(b == NULL)
b = temp;


a = a+b;
System.out.println(a);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top