【问题标题】:While code, Method, Int to boolean understandingwhile code, Method, Int 对布尔值的理解
【发布时间】:2020-11-25 07:23:41
【问题描述】:

我正在审查一些大学作业的代码,我们已经获得了一些示例来帮助我们。 我对下面的操作有点困惑,因为它使用的是赋值运算符而不是 .equals 或 == 方法。

如果我用 == 替换代码(并创建一个局部变量进行比较),代码将开始无限循环并显示默认值。

 int select = 0;
 
  do {
    
        switch (select) {
            case 1:
                Problem();
                break; 
            default:
            System.out.println("Invalid");
            break;
            } 

    } while ((select = getSelection()) !=3);

 public static int getSelection () { 
(Return function here with has.nextInt and scanner class to receive input)
}

根据我有限的理解,上面将“Select”分配给“getSelection”方法的值,它还声明不接受 3 的输入,例如此时 System.exit0。

我理解对了吗?

(根据要求提供更多示例) 我会按照以下方式做一些事情:

int select = 0; 
int select1 = 0; 
    do {

    switch (select) {
        case 1:
            Problem();
            break; 
        default:
        System.out.println("Invalid");
        break;
        } 
 } while (select == select1);

我试图想出一个与讲师示例的逻辑等价的方法,但似乎无法在不中断 while 循环的情况下做到这一点。

【问题讨论】:

  • 这个循环将一直运行,直到用户在输入中输入 3
  • 请在此处展示您如何使用==(select == getSelection()) !=3 不会编译,我不确定局部变量会如何改变它。
  • 我已经为你添加了示例:)
  • 在第二个示例中,您不会在 do-while 循环中更改任何 selectselect1 ——这就是它无限的原因。您需要在switch 之后添加select = getSelection(); - 然后循环运行,而getSelection() 返回0

标签: java loops methods while-loop


【解决方案1】:

在java中,(和其他“类似C”的语言)赋值的结果是赋值,即这个代码:

do {
    // other code
} while ((select = getSelection()) !=3)

等同于:

do {
    // other code
    select = getSelection();
} while (select != 3)

这种样式,称为内嵌条件,通常被认为是要避免的样式。

存在检查样式违规 - 请参阅 AvoidInlineConditionals

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 2011-08-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多