Home > Enterprise >  Loop when incorrect input is given?
Loop when incorrect input is given?

Time:11-07

So basically I've been trying to get this small simple code to work but I'm running into the problem of making a loop. What I want to happen is basically this: User enters an Integer, if its not an integer it will display an error and ask for an Integer until and Integer is given. I'm having a difficult time setting up a loop cause I don't quite know what to do. Im pretty new and dumb so this is probably really easy but I'm kind of an idiot and suck at this but I'm learning.

Here's what I have.

import java.util.Scanner;

public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
    int Index = scan.nextInt();
    scan.nextLine();
    System.out.println("Index = "   Index);
}
else if (scan.hasNextDouble()) {
    System.out.println("Error: Index is Double not Integer.");
                               }
else {
    System.out.println("Error: Index is not Integer.");
     }
}
}

CodePudding user response:

You can use while loop for that.

while (true) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter an Integer: ");
    if (scan.hasNextInt()) {
        int Index = scan.nextInt();
        scan.nextLine();
        System.out.println("Index = "   Index);
        break;
    } else if (scan.hasNextDouble()) {
        System.out.println("Error: Index is Double not Integer.");
    } else {
        System.out.println("Error: Index is not Integer.");
    }
}

CodePudding user response:

You need to use a loop (for or while) to your code. You can do it like this.

import java.util.Scanner;

 public class Loop {
     public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);

         while (true) {
             System.out.println("Enter an Integer: ");
             if (scan.hasNextInt()) {
                 int Index = scan.nextInt();
                 scan.nextLine();
                 System.out.println("Index = "   Index);
             } else if (scan.hasNextDouble()) {
                 System.out.println("Error: Index is Double not Integer.");
             } else {
                 System.out.println("Error: Index is not Integer.");
             }

             // add same condition to break the loop
         }

         // close the scanner
         scan.close()
     }

 }
  • Related