2015-11-23 109 views
2

我只是玩弄java,想做一个简单的程序,用户在哪里;我必须猜测/输入正确的数字,直到它是正确的。我该怎么做,程序可以继续运行,打印出“再次猜测”,直到用户输入正确的数字。也许是布尔?我不确定。这是我迄今为止所拥有的。简单的Java猜测程序。继续

import java.util.Scanner; 

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

    int myInt = 2; 

    // Create Scanner object 
    Scanner input = new Scanner(System.in); 

    //Output the prompt 
    System.out.println("Enter a number:"); 

    //Wait for the user to enter a number 
    int value = input.nextInt(); 

    if(value == myInt) { 
     System.out.println("You discover me!"); 
    } 
    else { 
     //Tell them to keep guessing 
     System.out.println("Not yet! You entered:" + value + " Make another guess"); 
     input.nextInt(); 

    } 
} 
+4

使用while循环,循环,直到值是正确的 – SomeJavaGuy

回答

6

你可能想使用while循环重复一些代码:

while (value != myInt) { 
    System.out.println("Not yet! You entered: " + value + ". Make another guess"); 
    value = input.nextInt(); 
} 
System.out.println("You discovered me!"); 
0

简单介绍了一个循环。

import java.util.Scanner; 

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

     int myInt = 2; 

     // Create Scanner object 
     Scanner input = new Scanner(System.in); 

     for(;;) { 
      //Output the prompt 
      System.out.println("Enter a number:"); 

      //Wait for the user to enter a number 
      int value = input.nextInt(); 


      if(value == myInt) { 

       System.out.println("You discover me!"); 
       break; 
      } 
      else { 
       //Tell them to keep guessing 
       System.out.println("Not yet! You entered:" + value + " Make another guess"); 

      } 
     } 

    } 
} 
+0

@ParkerHalo为什么你认为循环太早开始?我不知道规范。 – MikeCAT

+0

你编辑了这篇文章,因此循环现在不会太早启动......我仍然认为在他们知道什么是循环之前,将java-newlings的东西教给“for(;;)”和“break”并不好! – ParkerHalo

1

这个程序会做的伎俩:

public static void main(String [] args){ 
    int myInt = 2; 
    int value = 0; 
    Scanner input = new Scanner(System.in); 
    boolean guessCorrect = false; 
    while(!guessCorrect){ 
     System.out.println("Not yet! You entered:" + value + " Make another guess"); 
     value = input.nextInt(); 
     if(value == myInt){ 
      guessCorrect = true 
     } 
    } 
    System.out.println("You discover me!"); 
} 
+0

@ParkerHalo,感谢没有注意到。 –