当我输入特殊值时,如何执行程序

问题描述 投票:-3回答:2

最近我正在做一个代码,其中一个构造是如果我输入一个特殊值,程序将转到第5步(跳过几行)并返回到第1步。

public static void doall(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter VAL. -1 to end:");
    int val, a, b, c, count = 0;
    val = input.nextInt();
    PrintWriter output=new PrintWriter("Sum.txt");
    while (val != -1) {
        System.out.println("Enter a,b,c:");
        a = input.nextInt();
        b = input.nextInt();
        c = input.nextInt();
        int max, facto, even;
        max = findSum(a, b, c, output);
        output.println("The three original integers are " + a + " " + b + " " + c + " \n"
                + max + " is the sum");
        even = howmanyeven(max);
        output.println("there is/are "+even+ " even number(s)\n");
        while (a == 99) {

        }
    }
}

我应该在这之间放什么(a == 99),所以如果我输入99,它将跳过findsum方法和evennumber方法,然后回到开头,要求我输入a,b,c。所有答案都表示赞赏。

java
2个回答
0
投票

您需要首先将整数变量初始化为0,因为它们位于本地范围内,默认情况下不会初始化为0。我看到你可能试图在这一行做到这一点:

int val, a, b, c, count = 0;

但是,在这种情况下,只有count将取值0,您无法初始化变量,同时声明它们。

可能的是:

int val, a, b, c, count;
val = a = b = c = 0;

然后你可以这样做:

do {
    System.out.println("Enter a,b,c:");
    a = input.nextInt();
    b = input.nextInt();
    c = input.nextInt();
} while(a == 99);

<rest of code here>

希望这有帮助。

编辑:确保还为您的变量val分配一个其他值,否则您的循环将永远继续。


0
投票

在扫描仪中使用nextint()可能会出问题。尝试使用nexline()并将其转换为int。因此,如果你想在一行中使用','在字符串上使用split。例如,如果您可以在不同的行中输入数字

System.out.Print("enter a: ");
  Int a = Int.Parse(input.nextLine());
  System.out.Print("enter b: ");
  Int b = Int.Parse(input.nextLine()); 
  System.out.Print("enter c: ");
  Int c = Int.Parse(input.nextLine());
© www.soinside.com 2019 - 2024. All rights reserved.