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

}

}

It skips the line

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

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.

Thanks!

解决方案

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.

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

Just using:

String namez = scanz.next();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值