2015-04-16 4 views
0

Программа, которую я пытаюсь закончить, должна считываться в трех номерах от пользователя, а затем сохранять их в переменных num1, num2 и num3, чтобы они могли использоваться на этапах 2 и 3 Проблема, с которой я сталкиваюсь, заключается в том, что, когда программа проходит цикл после того, как пользователь вводит свои номера и пытается перейти к этапу 2 или 3, он говорит, что сначала должен выполнить первый шаг.
Это мой код, как прямо сейчас:Проблема с циклом и хранением данных в переменных

static Scanner console = new Scanner(System.in); 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int num1; 
     int num2; 
     int num3; 
     int input; 

     do { 
      boolean opt1Done = false; 
      System.out.println("Select your next step"); 
      System.out.println("1: Enter three numbers between 1 and 100."); 
      System.out.println("2: Order your number in ascending order"); 
      System.out.println("3: Determine if the three inputs form a triangle"); 
      System.out.println("4: Exit"); 

      int answer = console.nextInt(); 
      num1 = console.nextInt(); 
      num2 = console.nextInt(); 
      num3 = console.nextInt(); 
      input = console.nextInt(); 

      if (answer == 1) { 
       //do whatever for option 1 
       System.out.println("Enter a value for num1 between 1 and 100."); 
       System.out.println("Enter a value for num2 between 1 and 100."); 
       System.out.println("Enter a value for num3 between 1 and 100."); 

       opt1Done = true; 
      } else if (answer == 2) { 
       if (opt1Done) { 
        //...... do whatever to order the numbers 
        int[] arraynum; 
        arraynum = new int[3]; 

        arraynum[0] = num1; 
        arraynum[1] = num2; 
        arraynum[2] = num3; 

        Arrays.sort(arraynum); 

        int i; 

        for (i = 0; i < arraynum.length; i++) { 
         System.out.println("num:" + arraynum[i]); 
        } 

       } else { 
        System.out.println("you must complete Step 1 before Step 2"); 
       } 
      } else if (answer == 3) { 
       if (opt1Done) { 
        //... do whatever to determine if triangle or not 
        if (num1 + num2 > num3 && num1 + num3 > num2 && num2 + num3 > num1) { 
         System.out.print("TRIANGLE"); 
        } else { 
         System.out.print("NO TRIANGLE"); 
        } 
       } else { 
        System.out.println("you must complete Step 1 before Step 3"); 
       } 
       if (answer == 4) { 
        System.exit(0); 

       } 
      } 
     } while (input != 4); 
    } 
} 

мне нужно добавить еще один цикл или изменить один уже есть ли?

+1

Кажется, это домашнее задание. это? –

+0

его для проекта для класса программирования да @MuhammadSuleman – Will

+1

вы снова сломали код! Следите, когда вы редактируете свой вопрос;) – Robert

ответ

0

Перемещения булевой декларации opt1Done и номера за пределами цикла и чтения после каждой подсказки пользователя.

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.util.Arrays; 
import java.util.Scanner; 

public class ReadChar { 

    public ReadChar() { 
     // TODO Auto-generated constructor stub 
    } 

    static Scanner console = new Scanner(System.in); 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int num1 = 0; 
     int num2 = 0; 
     int num3 = 0; 
     boolean opt1Done = false; 

     while (true) { 

      System.out.println("Select your next step"); 
      System.out.println("1: Enter three numbers between 1 and 100."); 
      System.out.println("2: Order your number in ascending order"); 
      System.out 
        .println("3: Determine if the three inputs form a triangle"); 
      System.out.println("4: Exit"); 

      int answer = console.nextInt(); 

      if (answer == 1) { 
       // do whatever for option 1 
       System.out.println("Enter a value for num1 between 1 and 100."); 
       num1 = console.nextInt(); 

       System.out.println("Enter a value for num2 between 1 and 100."); 
       num2 = console.nextInt(); 
       System.out.println("Enter a value for num3 between 1 and 100."); 
       num3 = console.nextInt(); 

       opt1Done = true; 
      } else if (answer == 2) { 
       if (opt1Done) { 
        // ...... do whatever to order the numbers 
        int[] arraynum; 
        arraynum = new int[3]; 

        arraynum[0] = num1; 
        arraynum[1] = num2; 
        arraynum[2] = num3; 

        Arrays.sort(arraynum); 

        int i; 

        for (i = 0; i < arraynum.length; i++) { 
         System.out.println("num:" + arraynum[i]); 
        } 

       } else { 
        System.out 
          .println("you must complete Step 1 before Step 2"); 
       } 
      } else if (answer == 3) { 
       if (opt1Done) { 
        // ... do whatever to determine if triangle or not 
        if (num1 + num2 > num3 && num1 + num3 > num2 
          && num2 + num3 > num1) { 
         System.out.print("TRIANGLE"); 
        } else { 
         System.out.print("NO TRIANGLE"); 
        } 

       } else { 
        System.out 
          .println("you must complete Step 1 before Step 3"); 
       } 

      } 
      if (answer == 4) { 
       System.exit(0); 

      } 
     } 
    } 
} 
+0

спасибо, наконец, сработало! – Will

0

Вы не выполняете инструкции. Каждый раз, когда у вас есть шаг, программа заканчивается, и в следующий раз, когда вы ее запускаете, ничего не было сделано ранее.

Вам нужен внешний цикл для перебора команд:

public static void main(String[] args) { 

    int num1; 
    int num2; 
    int num3; 

    boolean opt1Done = false; 

    while (true) { 

     System.out.println("Select your next step"); 
     System.out.println("1: Enter three numbers between 1 and 100."); 
     System.out.println("2: Order your number in ascending order"); 
     System.out.println("3: Determine if the three inputs form a triangle"); 
     System.out.println("4: Exit"); 

     //rest of your code here 
    } 
} 
0

кажется, что вы должны цикл до пользователя выбрать вариант 4. Я не вижу никаких петель, которые охватывают возможности задавать вопросы.

0

вы устанавливаете условие в неправильном месте. , как я имею в виде первый контрольный ответа от пользователя затем принять эти 3 номера внутри первого условия, как

int answer = console.nextInt(); 
    if (answer == 1) { 
     //do whatever for option 1 
     System.out.println("Enter a value for num1 between 1 and 100."); 
     num1 = console.nextInt(); 
     System.out.println("Enter a value for num2 between 1 and 100."); 
     num2 = console.nextInt(); 
     System.out.println("Enter a value for num3 between 1 and 100."); 
     num3 = console.nextInt(); 
     opt1Done = true; 
    } 

и переместить эту линию вне цикла

boolean opt1Done = false; 
0

Надеется, что это помогает

  • Введен времени циклу и opt1True должны вне цикла
  • проверки является ответ 4 внутри ответа 3. Так повелся, что в другом, если бы то же самом вровень с другим ответом проверяет

    static Scanner console = new Scanner(System.in); 
    
        public static void main(String[] args) { 
         // TODO Auto-generated method stub 
    
         int num1 = 0; 
         int num2 = 0; 
         int num3 = 0; 
         boolean opt1Done = false; 
         while(true) { 
         System.out.println("Select your next step"); 
         System.out.println("1: Enter three numbers between 1 and 100."); 
         System.out.println("2: Order your number in ascending order"); 
         System.out.println("3: Determine if the three inputs form a triangle"); 
         System.out.println("4: Exit"); 
    
         int answer = console.nextInt(); 
         if (answer == 1) { 
          // do whatever for option 1 
          System.out.println("Enter a value for num1 between 1 and 100."); 
          num1 = console.nextInt(); 
    
          System.out.println("Enter a value for num2 between 1 and 100."); 
          num2 = console.nextInt(); 
    
          System.out.println("Enter a value for num3 between 1 and 100."); 
          num3 = console.nextInt(); 
    
          opt1Done = true; 
         } else if (answer == 2) { 
          if (opt1Done) { 
           // ...... do whatever to order the numbers 
           int[] arraynum; 
           arraynum = new int[3]; 
    
           arraynum[0] = num1; 
           arraynum[1] = num2; 
           arraynum[2] = num3; 
    
           Arrays.sort(arraynum); 
    
           int i; 
    
           for (i = 0; i < arraynum.length; i++) { 
            System.out.println("num:" + arraynum[i]); 
           } 
    
          } else { 
           System.out.println("you must complete Step 1 before Step 2"); 
          } 
         } else if (answer == 3) { 
          if (opt1Done) { 
           // ... do whatever to determine if triangle or not 
           if (num1 + num2 > num3 && num1 + num3 > num2 
             && num2 + num3 > num1) { 
            System.out.print("TRIANGLE"); 
           } else { 
            System.out.print("NO TRIANGLE"); 
           } 
          } else { 
           System.out.println("you must complete Step 1 before Step 3"); 
          } 
    
         } else if (answer == 4) { 
          System.exit(0); 
    
         } 
    
         } 
    
        } 
    
0

Все, что вам нужно было сделать, это добавить цикл while в вашу логику и изменить порядок.

boolean opt1Done = false; 
    int num1, num2, num3; 
    while(answer != 4){ 


    System.out.println("Select your next step"); 
    System.out.println("1: Enter three numbers between 1 and 100."); 
    System.out.println("2: Order your number in ascending order"); 
    System.out.println("3: Determine if the three inputs form a triangle"); 
    System.out.println("4: Exit"); 

    int answer = console.nextInt(); 


    if (answer == 1) { 
     //do whatever for option 1 
     System.out.println("Enter a value for num1 between 1 and 100."); 
     num1 = console.nextInt(); 
     System.out.println("Enter a value for num2 between 1 and 100."); 
     num2 = console.nextInt(); 
     System.out.println("Enter a value for num3 between 1 and 100."); 
     num3 = console.nextInt(); 
    opt1Done = true; 
    } 

            ... 


     if (answer == 4) { 
        System.exit(0); 

       } 
      } 
     } 
    } 

Ваша проблема была каждый раз, когда вы были зацикливание вы повторно декларирование и установив логическую переменную ложь. Кроме того, ваш console.nextInts() был не в том месте. Также делать это пока не нужно, потому что начальное значение ответа равно null и, следовательно, не равно четырем.

Смежные вопросы