【问题标题】:loop in if else condition in java [closed]在java中循环if else条件[关闭]
【发布时间】:2022-11-19 02:04:41
【问题描述】:

如何在 java 的 if else 条件中使用 while 循环,在下面的程序中,我在哪里可以使用可以给我所有值输出的循环。

import java.util.Scanner;
class hello {
    public static void add (int a) {
        if (a > 90) {
            System.out.print("A+");
        } else if (a > 80) {
            System.out.print("A");
        } else if ( a > 70) {
            System.out.print("B");
        } else if( a > 60) {
            System.out.print("C");
        } else if ( a >= 50) {
            System.out.print("Pass");
        } else if (a < 50) {
            System.out.print("Fail");
        }
    }
    
    public static void main( String [] args) {
        Scanner n = new Scanner (System.in);
        int a = n.nextInt();
        add(a);
    }
}

我在主函数中尝试了 while 循环,但它不起作用

【问题讨论】:

  • 向我们展示无效的代码?
  • 此外,您还应该修复缩进——其中大部分作为单行 if 语句是有意义的,但如果您要使用 {} 块,则它们应该一致地缩进。
  • public static void main( String [] args) { Scanner n = new Scanner (System.in); int a = n.nextInt();添加(一);诠释我= 0; while (i>6) { System.out.print(i);我++; } }}
  • 顺便说一句,您应该将其编辑到您的帖子中。 :)
  • i&gt;6 可能应该是 i&lt;6,因为条件最初不成立,根本不会运行。

标签: java loops class if-statement while-loop


【解决方案1】:

您需要使用hasNext() 方法查看是否有更多值。

Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
    add(scanner.nextInt());
}

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多