gpt4 book ai didi

Java 正在跳过一行(扫描仪中的字符串??)

转载 作者:行者123 更新时间:2023-12-03 06:44:35 24 4
gpt4 key购买 nike

我正在学习Java,而且还不是很深入,我不知道为什么,但Java似乎跳过了一行。我认为我所有页面的代码并不是真正必要的,所以我只会放置第一页和使用它时得到的结果。谢谢!

import java.util.Scanner;

public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);

System.out.println("\n\n\n\n\n" + secondObject);
}
}

它跳过该行

        String namez = scanz.nextLine();

控制台输出:(请原谅生日位,它是其他东西)

Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:




My name is and my birthday is 00/00/43

它不会给你提供名称的机会,它只是直接跳过并将名称视为空。如果有人可以的话请告诉我原因!我想学习Java,这个小烦恼阻碍了我。

谢谢!

最佳答案

问题是 nextLine 获取该行上的任何字符,而\n(换行符)是上面扫描仪输入留下的。

因此,它不会让您输入新内容,而是将\n 作为输入并继续。

要修复,只需将两个扫描仪背靠背放置,如下所示:

System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();

仅使用:

String namez = scanz.next();

也可以,但会限制名称为一个单词。 (又名仅名字)

关于Java 正在跳过一行(扫描仪中的字符串??),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158875/

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