For loop not a statement error - java

I'm trying to use for loops to check if a user is inputting an integer. The code will not let the user pass unless it is given an integer. I'm going to post a portion of my code, but if you think the error is outside of what I posted, I'll post the rest:
error:
not a statement
Code:
for (int prompt = 1; prompt < mainarray.length; prompt++) {
System.out.println("Please enter #" + prompt);
checkint = scan.nextInt();
// The error is pointing to the != in the following loop.
//I have check int declared above this code.
for (checkint != (int) checkint) {
System.out.println("This is not an integer, please input an integer");
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
}

You need an If statement to check this, not a for loop
if(checkint != (int)checkint)
{
System.out.println("This is not an integer, please input an integer");
}
Edit:
The Op said he/she is getting error as: java.util.InputMismatchException:null (in java.util.Scanner)
Solution:
You are using nextInt();. The java.util.Scanner.nextInt() method Scans the next token of the input as an int. if the next token does not match the Integer regular expression, or is out of range it will throw InputMismatchException.
You can use this code
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
try{
val = Integer.parseInt(s);
}
catch(NumberFormatException ex){
System.out.println("This is not an integer, please input an integer");
}
Even better,
try{
checkint = scan.nextInt();
}
catch(Exception ex){
System.out.println("This is not an integer, please input an integer");
}
Edit2
try
{
checkint = scan.nextInt();
mainarray[prompt]=checkint;
}
catch(Exception ex)
{
System.out.println("An integer is required;" + "input an integer please");
}

for(checkint != (int)checkint)
Isn't valid syntax for a for loop. That's a while loop. Consider this:
while (checkint != (int)checkint)
A while loop has one condition and will loop until that condition is not met. A for loop is actually just a while loop in disguise, but has three conditions:
starting point/initialization; condition; increment
However, you can leave the starting point and the increment blank to simulate a while loop.
HOWEVER this will put you in an ENDLESS LOOP. I don't know why you want a loop in the first place:
Finally, you should actually be doing this:
if (checkint != (int)checkint)

Change
for(checkint != (int)checkint)
as
for(;checkint != (int)checkint;)
From Doc
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed
once, as the loop begins.
When the termination expression evaluates to false, the loop
terminates.
The increment expression is invoked after each iteration through the
loop; it is perfectly acceptable for this expression to increment or
decrement a value.
BUT this will leads to an infinite loop in your code. So change it as
if (checkint != (int)checkint)

Related

Why isn't this while loop condition stopping the loop?

System.out.println("Please enter your grades: ");
while(scanner.nextInt() != -1){
numbers.add(scanner.nextInt());
}
I have a while-loop which is supposed to stop once a "-1" is entered by the user. Instead, a "-1" is inserted into my arraylist before being recognized. I would like to understand why the loop doesn't stop immediately upon detecting a "-1."
You're calling nextInt twice, and it returns a new int each time. Try this:
while(true){
int val = scanner.nextInt();
if (val == -1) {
break;
}
numbers.add(val);
}
Actually, You are typing input twice at each loop because scanner.nextInt() is called at two places in the while loop. Just call it one time and save typed value at each round. Below code does exactly what you want:
int nextInt;
while((nextInt = scanner.nextInt())!= -1){
numbers.add(nextInt);
}

What does happen inside this catch block?

I found this code online as a password loop game, it's working fine, but my question is: how?
What does happen in this catch block exactly?
I'm curious about this line specifically:
reader.next();
boolean loop = true;
Scanner reader = new Scanner(System.in);
System.out.println("PIN: ");
while (loop) {
try {
Integer Code = reader.nextInt();
if (Code == 8273) {
System.out.println("Access granted");
loop = false;
} else {
System.out.println("Access denied");
}
} catch (Exception e) {
System.out.println("Please enter a valid PIN!");
reader.next();
}
}
Edit : of course I did deliberately input a Non-integer input to cause the exception.
Edit2 :
When I removed that line, the program kept printing Please enter a valid PIN! For ever.
In fact, what the programmer really wanted here is to capture the next line of input, and verify whether that was a valid integer.
But the code is, admittedly, very confusing. And it relies on the fact that by default, when you "swallow" the next token with anything but .nextLine() with a Scanner, it relies on the current delimiter, which by default matches a newline.
Not good.
Here is a version which is more explicit:
String input;
int code;
while (true) {
System.out.print("PIN: ");
input = reader.nextLine();
try {
code = Integer.parseInt(input);
} catch (NumberFormatException ignored) {
// not an integer!
System.out.println("Enter a valid PIN!");
continue;
}
if (code == 8273)
break;
System.out.println("Access denied");
}
System.out.println("Access granted");
If nextInt throws an exception (because the value entered isn't an int), then the catch block is entered. The last line of which,
reader.next(); // <-- discards invalid token.
Removes the invalid token and then the loop iterates.
Also, don't box the Code1
int code = reader.nextInt();
1Using an Object type and then testing equality with == is a bad idea™. Also, by convention Java variable names start with a lower case letter.
The catch block simply catches the exception when anything other than an integer is entered. Since Code is an Integer, the input would have to be an integer. After catching the exception and printing the error, the reader moves to the next input until a proper value is entered, and the boolean loop becomes false, which ends the while loop at the end of the if statement once the correct value is entered.

Do-while, try-catch loop error

Im trying to write code for a school project, the main objective is to get the average gpa of a students semester depending on how many Subjects and Units you input, however, if I try typing 0, the program goes into an infinite try-catch loop with "You can only type positive numbers" Im using valueOf() because I want the user to be able to type "salir" which means exit, to exit the program.
Scanner LeerTeclado = new Scanner(System.in);
int n=0, i=0, suma=0, promedio=0;
String materia, cadena;
//---------------------------------------------------------------------------
out.println("---------------------------");
out.println("-- School Grades --");
out.println("---------------------------");
//---------------------------------------------------------------------------
out.println("\nType 'salir' to terminate the program");
out.println("-----------------------------------------");
out.print("Type the number of subjects to grade: ");
cadena = LeerTeclado.nextLine();
int z = 0;
if("salir".equals(cadena)){
System.exit(0);
}
if("Salir".equals(cadena)){
System.exit(0);
}
///////////////////////////////////////////////////////////////////
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
break;
}catch(NumberFormatException ex){
out.println("\n*You have entered non-numeric characters*");
out.print("\nPlease type the number of subjects again: ");
LeerTeclado.nextLine();
}
}while(true);
In the try block, before you write
continue;
but after "You can only type positive numbers," you should prompt the User for another line of input, and wait for the user to enter that.
The "continue" statement skips to the end of the loop and causes the 2nd part of the loop not to run. That is why the loop is running indefinitely.
Move reading cadena into the try block
int z = 0;
do {
try {
cadena = LeerTeclado.nextLine(); // <-- re-read
if ("salir".equalsIgnoreCase(cadena)) { // <-- you might test once.
System.exit(0);
}
// if ("Salir".equals(cadena)) {
// System.exit(0);
// }
z = Integer.valueOf(cadena); // <-- or this loops forever.
Alberto,
There are a few things that need to be changed in order to get this program to work the way you wish. Since you are a student I'm not going to solve it for you. I will answer your question, however.
When you type zero on the command line your program will execute from the z<=0 test down to the continue statement. The continue statement tells the code to ignore everything after and return to the beginning of the loop so it goes back to the beginning of the do statement and repeats. You need some way to end the loop.
May I suggest writing the program a little at a time and test as you go along. That is, write the part that's not in the loop. Once that works write a little something in the loop and test. Keep doing this until the programs works the way you want it to.
Good Luck
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
You want to use break
if(z <= 0){
System.out.println("...............................................");
System.out.println(" You can only type positive numbers ");
System.out.println("...............................................");
System.out.println("\n");
break;
}
continue just hops to the top of the if and keeps at it, same thing.

try/catch infinite loop? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
Help, I am completely new to java and I am trying to create a loop that will ask for an input from the user which is to be a number. If the user enters anything other than a number I want to catch the exception and try again to get the correct input. I did this with a while loop however it does not give the opportunity after the error for the user to type in anything it loops everything else but that. Please help me to see understand what is wrong and the correct way to do this... Thank you. This is what I have:
import java.util.Scanner;
import java.util.InputMismatchException;
public class simpleExpressions {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
while ( true ) {
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
} catch (Exception E) {
System.out.println("Please input a number only!");
} //end catch
} //end while
} //end main
while ( true )
{
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
}
catch (Exception E) {
System.out.println("Please input a number only!");
}
This suffers from several problems:
numOne hasn't been initialized in advance, so it will not be definitely assigned after the try-catch, so you won't be able to refer to it;
if you plan to use numOne after the loop, then you must declare it outside the loop's scope;
(your immediate problem) after an exception you don't call scanner.next() therefore you never consume the invalid token which didn't parse into an int. This makes your code enter an infinite loop upon first encountering invalid input.
Use keyboard.next(); or keyboard.nextLine() in the catch clause to consume invalid token that was left from nextInt.
When InputMismatchException is thrown Scanner is not moving to next token. Instead it gives us opportunity to handle that token using different, more appropriate method like: nextLong(), nextDouble(), nextBoolean().
But if you want to move to other token you need to let scanner read it without problems. To do so use method which can accept any data, like next() or nextLine(). Without it invalid token will not be consumed and in another iteration nextInt() will again try to handle same data throwing again InputMismatchException, causing the infinite loop.
See #MarkoTopolnik answer for details about other problems in your code.
You probably want to use a do...while loop in this case, because you always want to execute the code in the loop at least once.
int numOne;
boolean inputInvalid = true;
do {
System.out.println("Enter an expression.");
try {
numOne = keyboard.nextInt();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Please input a number only!");
keyboard.next(); // consume invalid token
}
} while(inputInvalid);
System.out.println("Number entered is " + numOne);
If an exception is thrown then the value of inputInvalid remains true and the loop keeps going around. If an exception is not thrown then inputInvalid becomes false and execution is allowed to leave the loop.
(Added a call to the Scanner next() method to consume the invalid token, based on the advice provided by other answers here.)

Java: Infinite loop using Scanner in.hasNextInt()

I am using the following code:
while (invalidInput)
{
// ask the user to specify a number to update the times by
System.out.print("Specify an integer between 0 and 5: ");
if (in.hasNextInt())
{
// get the update value
updateValue = in.nextInt();
// check to see if it was within range
if (updateValue >= 0 && updateValue <= 5)
{
invalidInput = false;
}
else
{
System.out.println("You have not entered a number between 0 and 5. Try again.");
}
} else
{
System.out.println("You have entered an invalid input. Try again.");
}
}
However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again."
Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement:
if (in.hasNextInt())
In your last else block, you need to clear the 'w' or other invalid input from the Scanner. You can do this by calling next() on the Scanner and ignoring its return value to throw away that invalid input, as follows:
else
{
System.out.println("You have entered an invalid input. Try again.");
in.next();
}
The problem was that you did not advance the Scanner past the problematic input. From hasNextInt() documentation:
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
This is true of all hasNextXXX() methods: they return true or false, without advancing the Scanner.
Here's a snippet to illustrate the problem:
String input = "1 2 3 oops 4 5 6";
Scanner sc = new Scanner(input);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println("Got " + num);
} else {
System.out.println("int, please!");
//sc.next(); // uncomment to fix!
}
}
You will find that this program will go into an infinite loop, asking int, please! repeatedly.
If you uncomment the sc.next() statement, then it will make the Scanner go past the token that fails hasNextInt(). The program would then print:
Got 1
Got 2
Got 3
int, please!
Got 4
Got 5
Got 6
The fact that a failed hasNextXXX() check doesn't skip the input is intentional: it allows you to perform additional checks on that token if necessary. Here's an example to illustrate:
String input = " 1 true foo 2 false bar 3 ";
Scanner sc = new Scanner(input);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
System.out.println("(int) " + sc.nextInt());
} else if (sc.hasNextBoolean()) {
System.out.println("(boolean) " + sc.nextBoolean());
} else {
System.out.println(sc.next());
}
}
If you run this program, it will output the following:
(int) 1
(boolean) true
foo
(int) 2
(boolean) false
bar
(int) 3
This statement by Ben S. about the non-blocking call is false:
Also, hasNextInt() does not block. It's the non-blocking check to see if a future next call could get input without blocking.
...although I do recognize that the documentation can easily be misread to give this opinion, and the name itself implies it is to be used for this purpose. The relevant quote, with emphasis added:
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
It is a subtle point, to be sure. Either saying "Both the hasNext and next methods", or "Both hasnext() and next()" would have implied that the companion methods would act differently. But seeing as they conform to the same naming convention (and the documentation, of course), it's reasonable to expect they act the same, and hasNext()
clearly says that it can block.
Meta note: this should probably be a comment to the incorrect post, but it seems that as a new user I can only post this answer (or edit the wiki which seems to be preferred for sytlistic changes, not those of substance).
Flag variables are too error prone to use. Use explicit loop control with comments instead. Also, hasNextInt() does not block. It's the non-blocking check to see if a future next call could get input without blocking. If you want to block, use the nextInt() method.
// Scanner that will read the integer
final Scanner in = new Scanner(System.in);
int inputInt;
do { // Loop until we have correct input
System.out.print("Specify an integer between 0 and 5: ");
try {
inputInt = in.nextInt(); // Blocks for user input
if (inputInt >= 0 && inputInt <= 5) {
break; // Got valid input, stop looping
} else {
System.out.println("You have not entered a number between 0 and 5. Try again.");
continue; // restart loop, wrong number
}
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
in.next(); // discard non-int input
continue; // restart loop, didn't get an integer input
}
} while (true);

Categories

Resources