运行时不显示 Java 字符串

标签 java string

我似乎无法弄清楚为什么当我运行这个时,字符串学院没有显示。我编译的时候没有任何错误。我究竟做错了什么?其他一切都正常。这可能是一个简单的修复,但我是新手,刚刚开始学习 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/

相关文章:

java - 如何获取 JVM 加载的所有包名称的列表

java - Spring Security如何允许匿名访问大多数站点限制某些操作

python - 当由 '..' Python 分隔时,将两个整数附加到列表

c++ - 连接字符串并作为参数传递?

java - 不同数据类型的数学运算是否不同?

java - 如何使用 Spring Cloud Gateway 自定义过滤器来过滤每个请求?

string - 如何将驼峰大小写字符串转换为蛇形大小写

将 int 复制到字符串

Java - 只识别字符串中的字母

java - 如何更改数组以使重复元素仅显示一次?