我似乎无法弄清楚为什么当我运行这个时,字符串学院没有显示。我编译的时候没有任何错误。我究竟做错了什么?其他一切都正常。这可能是一个简单的修复,但我是新手,刚刚开始学习 Java。
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String college;
String profession;
String animal;
String petname;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}
最佳答案
在age = Keyboard.nextInt();
之后调用keyboard.nextLine()
。
当前 int
值被读取为年龄,college = Keyboard.nextLine();
读取包含您的 int
的行的剩余部分,这是空的。所以正确的形式应该是:
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
避免额外调用 nextLine()
的其他可能解决方案是将整行作为字符串读取,然后将该字符串解析为整数,例如:
age = Integer.parseInt(keyboard.nextLine());
关于运行时不显示 Java 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004833/