user3056928
user3056928

Reputation: 55

Need to implement do, while loop to class

I'm trying to create a simple loop whereby there are 20 tables in the restaurant. A customer will be able to choose tables from 1 to 20. So I created an if else statement for it. But if a customer enters a number which is out of the boundary, it will print an error message. The thing is, I want it to re-ask the same question again if user enters wrongly, so I tried a do while loop. Problem is, the output is error-strewn. Can anyone help me with this?

public class MainRestaurant {

  public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);
    System.out.println("Please choose your table from 1-20.");

    int table;
    int x = 1;

    table = sc.nextInt();

    do{
      if(table >0 && table <21){
        System.out.println("Table chosen: " + table);
        x=2;
      }
      else{
        System.out.println("Wrong choice");
      }
    }while(x==1);
  }

Upvotes: 0

Views: 598

Answers (5)

Gopal Sharma
Gopal Sharma

Reputation: 16

Here is the modified version of ur code

public class MainRestaurant {

public static void main(String[] args) {

Scanner sc= new Scanner(System.in);
System.out.println("Please choose your table from 1-20.");

int table;
int x = 1;

do{
  table = sc.nextInt(); // every time the user will input the number
  if(table >0 && table <21){
    System.out.println("Table chosen: " + table);
    x=2;
  }
  else{
    System.out.println("Wrong choice");
  }
}while(x==1);

}

Upvotes: 0

Fr0z3n7
Fr0z3n7

Reputation: 2668

public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);
    System.out.println("Please choose your table from 1-20.");

    int table;
    int x = 1;

    do{
    table = sc.nextInt(); //put the sc.nextInt() inside de loop
    if(table >0 && table <21){
        System.out.println("Table chosen: " + table);
        x=2;
    }
    else{
        System.out.println("Wrong choice");
    }
    }while(x==1);
sc.close(); //don't forget to close the scanner

Upvotes: 0

lucian.pantelimon
lucian.pantelimon

Reputation: 3669

table = sc.nextInt(); should be in the do-while loop (i.e. after do{)

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

move this table = sc.nextInt(); line inside your do while loop

Upvotes: 0

ljgw
ljgw

Reputation: 2771

You should move the sc.nextInt() function in to the do-while loop.

do{
    table = sc.nextInt();
    if(table >0 && table <21){
        System.out.println("Table chosen: " + table);
        x=2;
    }
    else{
        System.out.println("Wrong choice");
    }

} while(x==1);

Upvotes: 2

Related Questions