在 java 中为一个输入组合多个 if 语句

combining several if statement for one input in java

我是 java 的初学者,谁能告诉我如何在一个输入中组合多个 if。

我的意思是这样的“

how old are you?"

当用户回答这个问题时,如果我的代码是:

public static void main(String[] args) {
    int age = 40;
    Scanner ageField = new Scanner (System.in);
         System.out.print("How old are you? ");
     if(ageField.nextDouble() > age ){
         System.out.print("you are over than 40 years old"); 

     }else if(ageField.nextDouble() < age ){
         System.out.print("you are less than 40");


     }else if(ageField.nextDouble() < 20 ){
         System.out.print("you are less than 20");
         }else {

             System.out.print("enter your age");
         }
    }
}

我的意思是答案应该基于给定的值,希望你明白我在说什么

您的代码无法正常工作,因为您在检查第一个条件 if...

时丢弃了用户输入

存储用户输入(顺便说一句,应该是整数而不是双精度数)

ageField.nextInt()

在变量中并在 if else 条件中使用它...无需多次调用 get Double

您的代码将无法运行,因为您多次调用 nextDouble()。相反,将年龄变量存储在 int 中并针对该年龄变量执行 if 语句。

Scanner sc = new Scanner (System.in);
System.out.print("How old are you? ");
int age = sc.nextInt();

if(age > 40){
  System.out.print("You are more than 40");
}else if(age < 40 && age >= 30){
  System.out.print("You are less than 40");
} else if(age < 30) {
  System.out.print("You are less than 30");
}
....

这实际上是 OP 要求的可能优化之一。一个 if 语句,可以根据需要重复使用。该程序将要求输入 ages 列表中的项目数:

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        List<Integer> ages = Arrays.asList("20", "40").stream().map(Integer::valueOf).collect(Collectors.toList());
        try (Scanner ageField = new Scanner(System.in))
        {
            System.out.print("How old are you? ");
            ages.forEach(e -> analyzeAge(ageField.nextInt(), e));
        }
    }

    private static void analyzeAge(int ageInput, int ageCompared)
    {
        String answer = null;
        if (ageInput > ageCompared)
        {
            answer = "You are older than " + ageCompared;
        }
        else if (ageInput < ageCompared)
        {
            answer = "You are younger than " + ageCompared;
        }
        else
        {
            answer = "You are exactly " + ageCompared + " years old";
        }
        System.out.println(answer);
    }
}