If input value is wrong, throw error and reenter
Hi, I am very new to java programming. I would like to let user enter the number greater than 0, and if i entered number is 0 then would inform user with message and let enter that number again. There are many inputs in program that have same conditions.
I would think of that code, but it says dublicate variables or something. Anyway i hope you get the idea....
Code java:
System.out.print( "Type first number: " );
int a= scanner.nextInt();
if (a<=0){
System.out.println("Must be more above 0");
System.out.print( "Type first number: " );
int a=scanner.nextInt();
}
System.out.print( "Type second number: " );
int b=scanner.nextInt();
if (b<=0){
System.out.println("Must be more above 0");
System.out.print( "Type first number: " );
int a=scanner.nextInt();
}
and so on....
Re: If input value is wrong, throw error and reenter
Can you show your entire code in the code tags, as there could be other issues?
As for the current problem, you only need to initialize variables once. That is, you only need to write int a = scanner.nextInt(); once. If you want to use the variable a again, just write a = scanner.nextInt(); I imagine you have the same problem for int b. The formatting when it prints to the console may be a bit awkward since you have 2 System.out.print(...) lines back to back. Either use println or \n at the end of the line.
It's not an error but try to avoid use the object name scanner because it is very similar to the method Scanner. You can still use it, just be careful on your capitalization.
Also, it would be better to write this in a loop (for, while or do-while) so you only have to write it out once and it becomes easier to follow. Here are some links to help you out with using them:
The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)
Re: If input value is wrong, throw error and reenter
Error, and cant run code: Duplicate local variable a. Appears when i ask to enter again value if previous one was wrong and store it into same variable.
Re: If input value is wrong, throw error and reenter
Please edit your post and wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
Re: If input value is wrong, throw error and reenter
Quote:
Originally Posted by
sabbath
Error, and cant run code: Duplicate local variable a. Appears when i ask to enter again value if previous one was wrong and store it into same variable.
I don't know what the problem is without seeing the code but if it's similar to your first post, then make sure you only declare each variable once.