我试图创建一个程序,允许用户输入他的名字,中间名和姓氏,但问题是,他可以选择不输入他的中间名,程序会解决它在这种情况下应该只显示名字和姓氏。 问题是我想得到我的" middle_name"扫描仪并将其放入一个变量,这将允许我整理两个"如果"陈述
以下是相关代码:
import java.util.Scanner;
public class Names {
public static void main(String[] args){
System.out.print("Enter your name : ");
Scanner first_name = new Scanner(System.in);
System.out.print("Enter your middle name : ");
Scanner middle_name = new Scanner(System.in);
System.out.print("Enter your last name : ");
Scanner last_name = new Scanner(System.in);
int x = Integer.parseInt(middle_name);
if(x == 0) {
System.out.println("First name : " + first_name);
System.out.println("Last name : " + last_name);
}
if(x > 0) {
System.out.println("First name : " + first_name);
System.out.println("Middle name : " + middle_name);
System.out.println("Last name : " + last_name);
}
}
}
答案 0 :(得分:3)
我想你想要做的是:
让一个扫描仪读取不同的行
检查middle_name是否为isEmpty()并且只有三个System.out语句
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name : ");
String first_name = in.nextLine();
System.out.print("Enter your middle name : ");
String middle_name = in.nextLine();
System.out.print("Enter your last name : ");
String last_name = in.nextLine();
System.out.println("First name : " + first_name);
if(!middle_name.isEmpty()) {
System.out.println("Middle name : " + middle_name);
}
System.out.println("Last name : " + last_name);
in.close();
}