gpt4 book ai didi

java - 如何修复 nextLine 错误以便打印两个单词?

转载 作者:行者123 更新时间:2023-12-02 01:05:02 26 4
gpt4 key购买 nike

下面的代码运行时效果很好,但如果您在“bands”问题中输入两个单词,您将只会打印出一个单词。

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.next();
System.out.println("I like >>" + bands + "<<too!");
}
}

最佳答案

Scanner 中的方法 next()将仅返回下一个 token 。

正如oracle文档中所写:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

默认分隔符是空格,因此如果您的乐队名称包含多个单词,它将不起作用。

用于读取整行输入用户nextLine()

如果您想分别使用两个带名称,请调用 nextLine() 两次以分别获取每个输入:

System.out.println("What are your favorite two bands?");
String band1 = scan.nextLine();
String band2 = scan.nextLine();
System.out.println("I like >>" + band1 + " and " + band2 + "<<too!");

在这种情况下,用户必须在每次输入后按“Enter”键。

编辑:

正如 Elliott Frisch 的评论中提到的,其他 readXXX 方法不会从输入流中删除行尾。看: stackoverflow.com/q/13102045/2970947

您可以对每个输入使用 nextLine() 或在每次读取后删除行尾。使用您的代码示例:

    Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
scan.nextLine();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
scan.nextLine();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<<too!");

API 引用:

next()

nextLine()

关于java - 如何修复 nextLine 错误以便打印两个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57740131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com