java.util.scanner - 如何在扫描仪中正确使用多个字符串变量?
问题描述
我是 Java 新手。我想我在扫描仪中错误地使用了字符串变量
我的代码
import java.util.Scanner;
public class AgeNextYear{
public static void main (String[ ] args){
String userName;
int age;
String city;
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
userName = scan.nextLine();
System.out.println("How old are you " + userName + "?");
age = scan.nextInt();
System.out.println("Which city do you live in?");
city = scan.nextLine();
System.out.println("Hello " + userName + " ,you are " + age + " and you live in " + city + ". Next year you will be " + (age + 1) + ".");
}
}
输出
What is your name?
Mark
How old are you Mark?
34
Which city do you live in?
Hello Mark ,you are 34 and you live in . Next year you will be 35.
如何修复我的代码,以便不跳过城市的用户输入?
解决方案
要解决此问题,请使用.next()
而不是.nextLine()
. 这是因为您的城市扫描仪上方已经有一个.nextLine()
(名称扫描仪)。这是最终的代码(有效):
import java.util.Scanner;
public class test{
public static void main (String[ ] args){
String userName;
int age;
String city;
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
userName = scan.next();
System.out.println("How old are you " + userName + "?");
age = scan.nextInt();
System.out.println("Which city do you live in?");
city = scan.next();
System.out.println("Hello " + userName + " ,you are " + age + " and you live in " + city + ". Next year you will be " + (age + 1) + ".");
}
}
推荐阅读
- perl - 从 Perl 调用静态 Java 方法
- python - 在 Bunch 类型对象中设置和获取属性
- reactjs - 如何使用 React 功能组件通过循环回调获取 api
- reactjs - 运行时类型错误:input.toLowerCase 不是函数
- rxjs - 有没有更好的方法来为两个依赖的 observables 编码
- mongodb - $push ed字段的mongodb总和
- javascript - 如何在页面加载时默认显示一个类,当悬停到另一个块时隐藏默认类并在悬停时显示另一个块
- python - 智能感知无法识别 Webelement 对象 python 变量
- node.js - 如果我试图查找并发送前面有 href 标记的链接,那么 title = $(element).find('h3').text() 的等价物是什么?
- java - Elasticsearch Windows UseConcMarkSweepGC 错误