Java跳过了一行(扫描仪中的字符串??) [英] Java is skipping a line (Strings in a Scanner ??)

查看:121
本文介绍了Java跳过了一行(扫描仪中的字符串??)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,但是对它的了解还不算很深,我也不知道为什么,但是Java似乎跳过了一行.我认为我所有页面中的代码都不是真正的必需品,因此我只放置第一页以及使用它时得到的结果.谢谢!

I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!

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();

控制台输出:(请问生日,那是其他东西)

Console output: (excuse the birthday bit, it is other stuff)

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,但是这种小烦恼阻碍了我的工作.

It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.

谢谢!

推荐答案

问题是nextLine获取行上的任何字符,并且\ n(换行符)保留在上面的扫描器输入中.

The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.

因此,与其让您输入新内容,不如将\ n作为输入并继续.

So instead of letting you enter something new, it takes the \n as the input and continues.

要解决此问题,只需将两个扫描仪背对背放置即可,

To fix, just put two scanners back to back like this:

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

只需使用:

String namez = scanz.next();

也可以,但是将名称限制为一个单词. (仅名)

will work too, but will limit the names to be one word. (aka first name only)

这篇关于Java跳过了一行(扫描仪中的字符串??)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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