在这种情况下,如何使用java-util-scanner处理换行符? [英] How can I handle new line character using java-util-scanner in this situation?

查看:61
本文介绍了在这种情况下,如何使用java-util-scanner处理换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的作业,正在制作一个简单的UI(不是GUI),并且正在使用扫描仪进行输入.

I have a simple homework assignment, I'm making a simple UI (not GUI) and I'm using scanner for input.

我想读取3个字符串(姓名,地址,社会保险号)

I want to read 3 strings (Name, address, social security number)

但是,如果用户没有插入任何内容,只需按Enter键,我的代码就会中断.而不是我需要的3个字符串,我得到了更多的字符串,它们错过了比赛.

If the user however does not insert anything simply presses enter, my code breaks. Instead of the 3 strings I need, I get more strings and they miss match.

Scanner input = new Scanner(System.in);
if (input.hasNext()) {
    name = input.nextLine(); 
} 
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
    address = input.nextLine(); 
} 
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
    ssnumb = input.nextLine(); 
} 

因此,如果用户按下Enter键,则创建一个新的换行符,输入就会溢出.如何避免这种情况或消除空白行?

So if user presses enter, creates a new line character, the input spills. How can I either avoid this or eliminate empty lines ?

示例:

输入

尼克

火星

一些数字

我会:

Name:

Address:尼克

Social Security Number:火星

推荐答案

类似以下内容:

Scanner input = new Scanner(System.in);
while(!input.next().isEmpty()) { // only when you enter literal string 
//do your scanner stuff here
}

这篇关于在这种情况下,如何使用java-util-scanner处理换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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