我是Java新手,最近在上周开始编码。我试图建立一些基本的东西并做了以下事情:
import java.util.Scanner;
public class App {
public static void main(String[] args){
// creating scanner object
Scanner userSex = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = userSex.nextLine();
System.out.println("Thank you, you entered " + sex );
// new scanner
Scanner userAge = new Scanner (System.in);
System.out.println("Are you a child or adult: ");
String age = userAge.nextLine();
System.out.println("You are a " + sex + " " + age);
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
}
}
不幸的是,只有代码的顶部才会运行。以下代码不会运行,即使我输入" child"也不会打印任何内容。或者"成人"。
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
答案 0 :(得分:2)
而不是
if(userAge.equals("child")) {
System.out.println("children");
}
else if(userAge.equals("adult")) {
System.out.println("adults");
}
这样做
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
答案 1 :(得分:1)
已经提到的一件事是你只需要一个扫描仪对象。没有必要为输入的每个字符串创建一个。主要问题是您正在测试userAge是否等于“child”或“adult”,但userAge是扫描程序对象。我想你的意思是写age.equals(“child”),因为age是输入的实际字符串。
答案 2 :(得分:0)
以下作品:
import java.util.Scanner;
public class App {
public static void main(String[] args){
//creating scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = in.next();
System.out.println("Thank you, you entered " + sex );
//new scanner
System.out.println("Are you a child or adult: ");
String age = in.next();
System.out.println("You are a " + sex + " " + age);
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
}
}
您只需使用一个扫描程序并调用next()
方法,而不是创建两个单独的扫描程序。我还将条件从if(userAge...
更改为if(age...
答案 3 :(得分:0)
无需创建两个扫描仪对象。只需创建一个扫描仪对象。 您也可以使用BufferedReader而不是Scanner。在您的代码中,您使用userAge.equals(“child”)。但这是不正确的,因为您存储扫描仪返回的值在年龄,使用年龄来比较if-else编码,如年龄.equals( “孩子”)
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = scanner.nextLine();
System.out.println("Thank you, you entered " + sex );
System.out.println("Are you a child or adult: ");
String age = scanner.nextLine();
System.out.println("You are a " + sex + " " + age);
if (age.equals("child")) {
System.out.println("children");
} else if (age.equals("adult")) {
System.out.println("adults");
}
参考链接:https://docs.oracle.com/javase/tutorial/essential/io/scanning.html