2015-01-24 2 views
-2

Я довольно новичок в java и им, не имея проблем с получением этого цикла? Код работает нормально, его просто, что после того, как пользователь правильно догадался, код останавливается.Мне нужен совет, чтобы исправить мой код HighLow в java

Вот мой код:

import java.util.Random; 
import java.util.Scanner; 

public class Chapter3HighLow { 
    public static void main (String[] args) { 

     Scanner input = new Scanner(System.in); 
     Random random = new Random(); //gives random numbers each time 
     int correctNum = random.nextInt(100); 
     int NumberOfTries = 0; // tells how many guesses it took 

     while (true) { 

      System.out.println("Hi! Please enter a number between 1-100! (if you would like to quit, please press -1)"); 
      int guess1 = input.nextInt(); 
      NumberOfTries++; //user enters their guesses 

      if (guess1 == (-1)) { 
       break; //breaks the loop if the user enters -1 
      } 

      if(guess1 < correctNum){ 
       System.out.println("The number inserted is too low!"); 

      } 
      else if(guess1 > correctNum){ 
       System.out.println("The number inserted is too high!"); 

      } 
      else if(guess1 == correctNum){ 
       System.out.println("The number you entered was Correct!!"); 
       System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took 
      } 
     }  
    } 
} 
+2

Что именно вы хотите сделать? Повторите цикл снова и снова, чтобы дать пользователю другое изменение для воспроизведения? – James

+0

перемещение правильного поколения в вашей петле. – Leonidos

+0

@ Leonidos Нет! Это все испортит! Ей понадобятся две петли, внешняя петля и внутренний цикл. –

ответ

0

Ваш окончательный else по-видимому, отсутствует break. Как

else if(guess1 == correctNum){ 
    System.out.println("The number you entered was Correct!!"); 
    System.out.println("It took you " + NumberOfTries + " tries"); 
    break; // <-- add this. 
} 

или вы могли бы сделать, что условие while. Что-то вроде,

int guess1 = -1; 
while (guess1 != correctNum) { 
    System.out.println("Hi! Please enter a number between 1-100! " 
     + "(if you would like to quit, please press -1)"); 
    guess1 = input.nextInt(); 
    if (guess1 == (-1)) { 
     break; 
    } 
    NumberOfTries++; 

    if (guess1 < correctNum) { 
     System.out.println("The number inserted is too low!"); 
    } else if (guess1 > correctNum) { 
     System.out.println("The number inserted is too high!"); 
    } else if (guess1 == correctNum) { 
     System.out.println("The number you entered was Correct!!"); 
     System.out.println("It took you " + NumberOfTries + " tries"); 
    } 
} 
+0

Хорошо, поэтому я изменил предположение1 = input.nextInt(); но теперь его высказывание о том, что поток «main» не был инициализирован? –

+0

Что еще вы изменили? –

-1

Неужели это действительно прекратится, если угадать это правильно?
enter image description here

+0

это остановилось для меня –

+1

Вам следует попробовать еще раз. Ваш код в порядке! – CodeWalker

1

Я не совсем уверен, что вы просите, однако, от того, что я могу понять, вы хотите получить вашу игру в цикле непрерывно до тех пор, пока пользователь не хочет, чтобы остановить воспроизведение. Итак, вы ищете метод, который дает пользователю выбор, хотите ли они снова играть. Я предлагаю использовать boolean. Следующий код демонстрирует это для примера:

import java.util.Random; 
import java.util.Scanner; 
public class Chapter3HighLow { 
private static boolean playAgain(){ 
    Scanner sc = new Scanner(System.in); 
    String usrInput = ""; 
    System.out.println("Play again? (Y/N)"); 
    usrInput = sc.next(); 
    if(usrInput.equalsIgnoreCase("Y")){ 
     return true; 
    } 
    else if(usrInput.equalsIgnoreCase("N")){ 
     return false; 
    } 
    else{ 
     return false; 
    } 
} 
public static void main (String[] args) { 
    Scanner input = new Scanner(System.in); 
    Random random = new Random(); //gives random numbers each time 
    int correctNum = random.nextInt(100); 
    int NumberOfTries = 0; // tells how many guesses it took 
    int guess1 = 0; 
    do{ 
     do{ 
      System.out.println("Please guess a number between 1-100!"); 
      guess1 = input.nextInt(); 
      NumberOfTries++; //user enters their guesses 
      if (guess1 == (-1)) { 
       break; //breaks the loop if the user enters -1 
      } 
      if(guess1 < correctNum){ 
       System.out.println("The number inserted is too low!"); 
      } 
      else if(guess1 > correctNum){ 
       System.out.println("The number inserted is too high!"); 
      } 
      else if(guess1 == correctNum){ 
       System.out.println("The number you entered was Correct!!"); 
       System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took 
      } 
     }while(guess1 != correctNum); 
     correctNum = random.nextInt(100); 
     NumberOfTries = 0; 
    }while(playAgain() == true); 
} 
} 

Подробнее о методах here.

Узнать больше о boolean тип данных here.

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