10次​​运行后如何终止申请?

时间:2015-01-07 17:15:36

标签: java

我想在您输入0 10次后让应用程序停止运行。我是编程课,而且非常糟糕。任何帮助表示赞赏:)

import java.util.Scanner;

class Areyouboredyet
{

  public static void main (String[] args ) 
  {

    Scanner input = new Scanner(System.in);
    int value;             

    System.out.println( "Are you bored yet? 1 for yes; 0 for no." );
    value = input.nextInt();

    while ( value != 1 )    
    {
      System.out.print("Are you bored yet? 1 for yes, 0 for no.");
      value = input.nextInt(); 
    }

    System.out.println( "Finally!");
  }
}

3 个答案:

答案 0 :(得分:4)

有一个单独的计数器,可以计算您提出问题的次数,并在每次提出问题时递增。将此变量添加到while条件(例如while(value != 1 && timesAsked < 10)),一旦变量大于10,它将终止循环。

答案 1 :(得分:2)

  int count = 0;
  System.out.println( "Are you bored yet? 1 for yes; 0 for no." );
    value = input.nextInt();

  while ( value != 1 && count < 10)    

  {
    count = count + 1;
    System.out.print("Are you bored yet? 1 for yes, 0 for no."); value = input.nextInt(); 

  }

  System.out.println( "Finally!");
}

答案 2 :(得分:1)

有几种方法可以做到这一点,但它们基本上归结为同样的事情:跟踪被问到的次数。

我最喜欢这样做的方式是这样的:

... //Initializing variables and objects and whatnot
for (int times = 0; times < 10 && value != -1; times++) {
  ... //Your code inside, which presumably changes 'value'.
}
... //Whatever comes after

这样做会自动跟踪,增加等一个名为times的变量,该变量记录您完成循环的次数。当达到10或value不是-1时,它会跳出循环并继续。正文应与while循环中的正文相同。