如何在循环后重新启动代码

时间:2014-02-04 20:57:05

标签: java

import java.util.Scanner; 

public class Testing { 

    public static void main(String[] args) {

        int i = 0, j = 0;

        while(i>=0){
        Scanner input=new Scanner(System.in);

        System.out.println("Enter a number:");        
        i = input.nextInt();

            for(;i>0;i--){

                for (j=i; j>0; j--){

                 System.out.print("*");
                 }
                 System.out.println(" ");
            }
        }  
    }
}

是代码,在我输入数字后打印结果,它应该问我是否要再次尝试或退出选择1.again 2.exit,我不知道如何重启代码从最开始。任何帮助都会很好。

7 个答案:

答案 0 :(得分:1)

要表示您要求的行为(因为您不想让用户第一次继续),我建议您使用do {} while;循环:

int redo = 0;
do {
    //Initialize your variables
    //Read the Input
    //Process the Input

    System.out.println("Enter 1 to do it again:");
    redo = input.nextInt();
} while(redo == 1);

答案 1 :(得分:0)

将所有内容包含在另一个循环中。这样你就可以从头开始重新启动它。

答案 2 :(得分:0)

当您需要循环时,请使用循环。 如果需要两个嵌套循环,则使用2个嵌套循环。

类似伪造的代码:

loopy
{
  ask for input

  loopy
  {
      process input
  }
}

答案 3 :(得分:0)

你可以使用开关盒做

 String choice;
        switch (choose) {
            case 1:  choice = "start again ";
                     break;
            case 2:  choice = "exit";
                     break;

            default: choice = "Invalid match";
                     break;
        }

并根据选择的价值,你可以运行你的循环

答案 4 :(得分:0)

使用while循环。在while循环中将您想要“重启”的内容包含在内。

作为循环的条件,使用一个布尔值,一旦想要中断循环并关闭程序就更新。例如:当用户按下某个键时,您的循环将结束。

答案 5 :(得分:0)

尝试这样的事情:

while(true){
      //get input
    for(){
        //process output
    }
    //get input for continue or exit
    if(input is exit){
        //break out of while loop
    }
}

答案 6 :(得分:0)

do {

//get user input
if (input==2){
System.exit(1);
}
//
else{
System.out.print(input);
}
//
} while(!done);

您只需将现有代码放入另一个循环中,然后就可以设置何时需要退出多个不同退出方法的条件。

System.exit(1);
done=false;
相关问题