控制流条件

huangapple go评论139阅读模式
英文:

Control Flow Condition

问题

我无法理解为什么 "For" 循环会继续执行,即使满足条件并应用了 "break" 语句。

代码:

class ProgramControlStatements {
    public static void main(String[] args) throws java.io.IOException {
        System.out.println("Menu: ");
        System.out.println("Choice: ");
        System.out.println("1: If/Else");
        System.out.println("2: Switch");
        for(int i = 0; i < 5; i++) {
            chooseOption();
        };
    };

    static void chooseOption() throws java.io.IOException{
        char choice = (char) System.in.read();
        switch(choice){
            case 'a':
                System.out.println("Computer control statement: If/Else");
                break;
            case 'b':
                System.out.println("Computer control statement: Switch");
                break;
            default:
                System.out.println("No valid option");
        };
    }
}

预期结果:

如果选择字符 a,则打印 "If/Else",并期望继续输入直到 i<5

Computer control statement: If/Else

实际结果:

第一次输入 -> a
Computer control statement: If/Else

No valid option

第二次输入 -> b
Computer control statement: Switch

No valid option

第三次输入 -> a
Computer control statement: If/Else

程序结束。

我希望 "default" 语句被跳过,因为应用了 "break" 语句。
这是否是因为 "System.in.read()" 返回了一个换行符?
我认为 "while" 循环和 "do-while" 循环的行为应该是相同的?

英文:

I fail to understand why For loop keeps executing, if condition meet and break statement applied.

Code:

class ProgramControlStatements {
    public static void main(String[] args) throws java.io.IOException {
        System.out.println(&quot;Menu: &quot;);
        System.out.println(&quot;Choice: &quot;);
        System.out.println(&quot;1: If/Else&quot;);
        System.out.println(&quot;2: Switch&quot;);
        for(int i = 0; i &lt; 5; i++) {
            chooseOption();
        };
    };

    static void chooseOption() throws java.io.IOException{
        char choice = (char) System.in.read();
        switch(choice){
            case &#39;a&#39;:
                System.out.println(&quot;Computer control statement: If/Else&quot;);
                break;
            case &#39;b&#39;:
                System.out.println(&quot;Computer control statement: Switch&quot;);
                break;
            default:
                System.out.println(&quot;No valid option&quot;);
        };
    }
}

Expected result:

If char a chosen, print "If/Else" and expect next input until i<5

Computer control statement: If/Else

Actual result:

First Input -> a
Computer control statement: If/Else

No valid option

Second input -> b
Computer control statement: Switch

No valid option

Third input -> a
Computer control statement: If/Else

Program ends.

I expect default statement to be skipped since break statement is applied.
Is this happening as System.in.read() returns a new line?
I think same behaviour is to be expected from while; do-while loops?

答案1

得分: 3

不像 @Arvind Kumar Avinash 所说的那么简单,根据您的操作系统,每行结束后可能会遇到 \r(回车)、\n(换行)或者两者都有 \r\n。因此,仅仅添加另一行 System.in.read() 是一种不总是有效的解决方法。

我建议使用 Scanner,就像这里建议的一样:https://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner。

附注:作为对评论中请求的回答,我想指出,当我想解析输入并且不关心性能时,我总是尝试使用 Scanner。当我关心性能时,我会使用 BufferedReader。从不直接使用 System.in。您可以在这里提供的答案中阅读更多信息:https://stackoverflow.com/a/21698084/2477456。

英文:

It's not as easy as @Arvind Kumar Avinash says, depending on your OS you may encounter either a \r (carriage return), \n (new line) or both \r\n after every line.

So just adding another System.in.read() line is a workaround that may not always work.

I suggest using Scanner instead, as suggested here: https://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner.

LE: As an answer to a request in the comment, I would like to specify that I always try to use Scanner when I want to parse my input and don't mind the performance. When I mind performance, I use BufferedReader. Never System.in directly. You can read more in the answers provided here https://stackoverflow.com/a/21698084/2477456.

答案2

得分: 1

我相信答案是迄今为止提供的两个答案之间的综合。

对于快速解决,@Arvind Kumar Avinash非常优秀。

根据@Valdrinium更深入地研究问题,可能会考虑其他选择。

我对选择@Arvind Kumar Avinash作为最终解决方案持怀疑态度,尽管在这种情况下它解决了问题。

能否有管理员提供帮助?

英文:

I believe the answer is a combination between the 2 answers offered so far.

For a quick fix, @Arvind Kumar Avinash is very good.

Looking more in to the problem as @Valdrinium specifies alternatives might be considered.

I am sceptical on choosing @Arvind Kumar Avinash as definitive, although it solve the problem in this instance.

Can an admin help?

答案3

得分: 0

以下是您提供的代码的翻译部分:

这是因为存在悬空的换行符。只需再次添加System.in.read();,如下所示,以消耗悬空的换行符,例如(char) System.in.read()仅消耗了a,而不会消耗您在输入a之后按下的<kbd>Enter</kbd>字符。

public class Main {
    public static void main(String[] args) throws java.io.IOException {
        System.out.println("菜单:");
        System.out.println("选择:");
        System.out.println("1:If/Else");
        System.out.println("2:Switch");
        for (int i = 0; i < 5; i++) {
            chooseOption();
        }
    }

    static void chooseOption() throws java.io.IOException {
        char choice = (char) System.in.read();
        System.in.read();// 添加这行
        switch (choice) {
            case 'a':
                System.out.println("计算机控制语句:If/Else");
                break;
            case 'b':
                System.out.println("计算机控制语句:Switch");
                break;
            default:
                System.out.println("无效选项");
        }
    }
}

一个示例运行:

菜单:
选择:
1:If/Else
2:Switch
a
计算机控制语句:If/Else
b
计算机控制语句:Switch
a
计算机控制语句:If/Else
b
计算机控制语句:Switch
a
计算机控制语句:If/Else

英文:

It's happening because of the dangling line break character. Just add System.in.read(); once again as shown below to consume dangling line break character e.g. (char) System.in.read() consumes just a but not the <kbd>Enter</kbd> character that you press after a.

public class Main {
	public static void main(String[] args) throws java.io.IOException {
		System.out.println(&quot;Menu: &quot;);
		System.out.println(&quot;Choice: &quot;);
		System.out.println(&quot;1: If/Else&quot;);
		System.out.println(&quot;2: Switch&quot;);
		for (int i = 0; i &lt; 5; i++) {
			chooseOption();
		}
	}

	static void chooseOption() throws java.io.IOException {
		char choice = (char) System.in.read();
		System.in.read();// Add this line
		switch (choice) {
		case &#39;a&#39;:
			System.out.println(&quot;Computer control statement: If/Else&quot;);
			break;
		case &#39;b&#39;:
			System.out.println(&quot;Computer control statement: Switch&quot;);
			break;
		default:
			System.out.println(&quot;No valid option&quot;);
		}
	}
}

A sample run:

Menu: 
Choice: 
1: If/Else
2: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else

huangapple
  • 本文由 发表于 2020年9月12日 18:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63859557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定