带有切换条件和循环的方法[重复]

问题描述 投票:0回答:1
我有一个带有开关盒的方法。只要给出的答案有误,就会通过默认的Case调用该方法。问题在于,如果程序最终收到正确答案,则其余代码(在切换之后)将执行额外的时间,该次数等于其收到错误答案的次数。例如,如果连续给出3个错误答案,则当最终给出正确答案时,system.out.println(a);将被执行4次(3个错误答案= 3次和1个正确答案)。

public void getAnswer() { System.out.println("Give an answer"); String answer = reader.nextLine(); switch(answer) { case "a": ans = 10; break; case "b": ans = 20; break; case "c": ans = 30; break; default: System.out.println("Please give a correct answer!"); getAnswer(); } System.out.println(a); }

java loops switch-statement
1个回答
0
投票
您可以尝试这个

static Scanner scanner = new Scanner(System.in); public static void getAnswer() { System.out.println("Give an answer"); String answer = scanner.nextLine(); int ans = -1; switch (answer) { case "a": ans = 10; break; case "b": ans = 20; break; case "c": ans = 30; break; default: System.out.println("Please give a correct answer!"); getAnswer(); return; } System.out.println(ans); }

,输出:

Give an answer d Please give a correct answer! Give an answer d Please give a correct answer! Give an answer a 10

© www.soinside.com 2019 - 2024. All rights reserved.