im java中的begginer,有人能告诉我如何在一个输入中组合几个。
我的意思是这样的"
你多大了几岁?"
当用户回答这个问题时,如果我的代码是:
,则可以使用几个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");
}
}
}
我的意思是答案应该基于给定的值,希望你得到我说的话
答案 0 :(得分:1)
您的代码无效,因为您正在丢弃用户输入,检查第一个条件如果 ......
存储用户输入(BTW应该是整数而不是双精度)
ageField.nextInt()
在一个变量中并使用if else条件......不需要多次调用get double
答案 1 :(得分:1)
这实际上是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);
}
}
答案 2 :(得分:0)
您的代码无效,因为您多次致电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");
}
....