【问题标题】:Java if else statements help please?Java if else 语句有帮助吗?
【发布时间】:2015-11-17 01:23:01
【问题描述】:

我正在尝试输出它,以便打印 num1、num2、num3、num4 或 num5 = 999 并停止扫描仪输入继续,因为它没有使用我的代码。希望这是有道理的,您能提供帮助将不胜感激。

package a5q4;
import java.util.Scanner;
/**
 *
 * @author Drew
 */
public class A5Q4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num1;
        int num2;
        int num3;
        int num4;
        int num5;

        System.out.println("Enter different numbers between 1 and 100");
        num1 = input.nextInt();
        if (num1 == 999) {
            num2 = 0;
            num3 = 0;
            num4 = 0;
            num5 = 0; 
        }
        else {
            num2 = input.nextInt();
        }
        if (num2 == 999) {
            num3 = 0;
            num4 = 0;
            num5 = 0;
        }  
        else {
            num3 = input.nextInt();
        }
        if (num3 == 999) {
            num4 = 0;
            num5 = 0;   
        }
        else {
            num4 = input.nextInt();
        }
        if (num4 == 999) {
            num5 = 0;   
        }
        else {
            num5 = input.nextInt();
        }

【问题讨论】:

  • 似乎选择 999 是一个奇怪的退出退出条件。另外,你能用while这样的循环来解决这个问题吗?
  • 不,没有循环刚刚开始学习,谢谢

标签: java if-statement


【解决方案1】:

首先,您可以在一行中声明初始化多个int(s)。如果我理解您的问题,您想测试给定的num 值是否不是999 并且如果不是,请阅读nextInt。您需要嵌套您的 if(s) 来使用单独的 num 值。类似的,

int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0;

System.out.println("Enter different numbers between 1 and 100");
num1 = input.nextInt();
if (num1 != 999) {
    num2 = input.nextInt();
    if (num2 != 999) {
        num3 = input.nextInt();
        if (num3 != 999) {
            num4 = input.nextInt();
            if (num4 != 999) {
                num5 = input.nextInt();
            }
        }
    }
}

如果没有 boolean 否定 (!),它必须在嵌套的 else(s) 中,

System.out.println("Enter different numbers between 1 and 100");
num1 = input.nextInt();
if (num1 == 999) {
} else {
    num2 = input.nextInt();
    if (num2 == 999) {
    } else {
        num3 = input.nextInt();
        if (num3 == 999) {
        } else {
            num4 = input.nextInt();
            if (num4 == 999) {
            } else {
                num5 = input.nextInt();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多