Scanner的问题 - Java [英] Problems with Scanner - Java

查看:87
本文介绍了Scanner的问题 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取包含多个单词的字符串,即。洛杉矶或纽约市。对于离开和到达使用scanner.next()只读取第一个,如果有两个单词并在变量之间拆分。 nextLine()也没有太大的运气。这是我的代码:

I'm trying to have the option of reading a string with multiple words, ie. Los Angeles or New York City. Using scanner.next() for "Departure" and "Arrival" would only read the first one if there were two words and split them between variables. nextLine() has not been much luck either. Here's my code:

            System.out.print("\nEnter flight number: ");
            int flightNumber = Integer.valueOf(scanner.nextLine());
            System.out.print("\nEnter departing city: ");
            String departingCity = scanner.nextLine();
            System.out.print("\nEnter arrival city: ");
            String arrivalCity = scanner.nextLine();

我知道这很简单,但我还没弄清楚。

I know it's something simple but I haven't figured it out.

这是输入/输出w /上面的代码:

Here's the input/output w/ the code above:

输入航班号:29

输入离境城市:(立即跳至下一行)

Enter departing city: (immediately it skips to the next line)

输入抵达城市:

----我真正想要的是什么----

---- What I'm really going for ----

输入航班号:29

进入离境城市:洛杉矶(能够在不跳过下一个输入的情况下输入多个单词)

Enter departing City: Los Angeles (be able to type multiple words without it skipping the next input)

输入抵达城市:堪萨斯城

Enter arrival city: Kansas City

推荐答案

你的问题是next()没有读取回车符,它会被你的下一个next()或nextLine自动读取()。一直使用nextLine()并将输入转换为整数:

Your problem is that next() does not read the carriage return and it gets automatically read by your next next() or nextLine(). Use nextLine() all time and convert input to integer:

public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    System.out.print("\nEnter flight number: ");
    int flightNumber = Integer.valueOf(scanner.nextLine());
    System.out.print("\nEnter departing city: ");
    String departingCity = scanner.nextLine();
    System.out.print("\nEnter arrival city: ");
    String arrivalCity = scanner.nextLine();

}

这篇关于Scanner的问题 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆