• 0

How the heck do I make a user's input go through the loop again?


Question

I had a tough time wording this question... the situation Im having is kinda specific.

Just a brief overview, I need to ask the user for two inputs: 1) choose a loop to use(1-for 2- while 3-do while). Entering 0 terminates the whole program. 2) After choosing a loop, enter an integer to begin conversion (the loops will convert the integer into ASCII characters, which I've already made).

Here's the issue Im having: If the user's first input is above 3, I want the user to input a value again and again until its either 0, 1, 2, or 3. Once the user FINALLY enter's a valid integer, the conversion loops begin. I wrote an else if statement that tells the user to enter another integer (if they didnt enter 0-3). This is the troubling part. After a new integer is entered, nothing happens. How do I make this new integer go through the entire if else statement? 

Here is what I currently have:

 

import java.util.Scanner;

public class Testing{
     public static void main(String[] args) {
          System.out.println(" Select a Loop type 1: for Loop, 2: while, 3: do-while ");
          Scanner sc = new Scanner(System.in);

          int input = sc.nextInt();
          int a = 33;
          if (input == 1){

          for (a = 33; a <= 126; a++){
            char myChar = (char) a;
            System.out.println(a + "=" + myChar );
          }
          }else if(input == 2){

          while (a <= 126){
            char myChar = (char) a;
            System.out.println(a + "=" + myChar );
            a++;
          }

          } else if(input == 3){

          do{
            char myChar = (char) a;
            System.out.println(a + "=" + myChar);

            a++;
          }
          while (a <= 126);
          
          } else if (input > 3){
            System.out.println("Choose between 0, 1, 2, or 3");
            input = sc.nextInt();

            //I want this new integer to go through the if else process again.

        }
   }

}

1 answer to this question

Recommended Posts

  • 0
Scanner scanner = new Scanner(System.in);
int input;

do {
    System.out.println(" Select a Loop type 1: for Loop, 2: while, 3: do-while ");
    input = sc.nextInt();
} while(input > 3); //This while conditional is only used after the first do

//Consider using a switch instead of if else statements and also think about negative integer input handling

A do while loop should handle the problem just fine since it checks the input after the first and next do loops.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.