简体   繁体   English

Java,如果其他语句有帮助吗?

[英]Java if else statements help please?

I am trying to output it so it prints if either num1, num2, num3, num4 or num5 = 999 and stops the scanner input from continuing as it does not with my code. 我正在尝试输出它,以便在num1,num2,num3,num4或num5 = 999时打印并停止扫描程序输入,因为它不包含我的代码。 Hope this makes sense and you can help it would be very appreciated. 希望这是有道理的,您可以提供帮助,我们将不胜感激。

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();
        }

First, you can declare and initialize multiple int (s) on one line. 首先,您可以在一行上声明初始化多个int If I understand your question, you want to test if a given num value isn't 999 and if it isn't then read the nextInt . 如果我理解您的问题,您想测试给定的num值是否不是999 如果不是,那么请读取nextInt You'll need to nest your if (s) to do it with individual num values. 您需要嵌套if (s)来使用单个num值。 Something like, 就像是,

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();
            }
        }
    }
}

Without boolean negation ( ! ), it would have to be in nested else (s), 如果没有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();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM