2016-04-27 181 views
-3

我正在尝试编写代码,要求我插入我的年龄。如果它在10岁以下,我希望它再问我3次。如果它在10以上,它会说“欢迎”。我无法做到这一点。循环扫描仪

package newProject; 
import java.util.Scanner; 
    public class mainclass { 
     public static void main(String[] args) { 

      System.out.println("Enter your age"); 
      Scanner age= new Scanner(System.in); 

      int userage= age.nextInt(); 
      if(userage<10){ 
       for(int x = 3;x<3;x++){ 
        System.out.println(userage+ "is too young"); 
        System.out.println("Enter your age"); 
        int userage1= age.nextInt(); 
       } 
      }else{ 
       System.out.println("welcome"); 
      } 
     } 
    } 
+3

除了严重的代码格式问题,我们需要更多的信息,而不仅仅是“它无法做到这一点”。请参阅[如何提问](http://www.stackoverflow.com/help/how-to-ask)。 – CodeMouse92

回答

2

无论程序的意义如何,您的错误都是您在x变量中设置的值。您必须将迭代3次的值设置为0。

System.out.println("Enter your age"); 
    Scanner age= new Scanner(System.in); 

    int userage= age.nextInt(); 
    if(userage<10) { 
    // You have to set x to 0 not 3 
    for(int x = 0;x<3;x++){ 
     System.out.println(userage + "is too young"); 
     System.out.println("Enter your age"); 
     int userage1= age.nextInt();} 
    } 
    else{ 
     System.out.println("welcome"); 
    } 
+0

我只是练习java我今天自己学习所以... 当我写你的代码,机器打印我写的第一个答案,例如,如果我写5然后它无所谓我接下来写什么它保持打印“ 5太年轻了“ –

+0

这是因为如果你看到for循环中的第一个打印,你使用了userage变量,但是在你读取了userage1变量后,如果你想解决这个问题,第二个userage应该是这样的:userage = age.nextInt();而不是一个新的变量userage1。你明白我说的吗? –

0

这里的问题:

for(int x = 3;x<3;x++) 

你已经设置for循环运行,只要x小于3,但你声明x等于3。因此,条件x<3永远不会满足,所以循环永远不会运行。下面是你应该做的:

for (int x=0; x<3; x++) 

顺便说一下,请使用适当的缩进格式化您的代码。没有缩进就很难阅读。

0
package newProject; 
import java.util.Scanner; 
public class mainclass { 
    public static void main(String[] args) { 
     System.out.println("Enter your age"); 
     Scanner age= new Scanner(System.in); 

     int userage= age.nextInt(); 
     if(userage<10){ 
      for(int i = 0;i<3;i++){ 
       System.out.println(userage+ "is too young"); 
       System.out.println("Enter your age"); 
       int userage1= age.nextInt(); 
      } 
     } 

     else{ 
      System.out.println("welcome"); 
     } 
    } 
} 
+0

这实际上只是现有答案的重复。 – Pang