java - 在不使用 NextLine 的情况下读取字符串中的空格作为输入
问题描述
说明:
我在下面的代码中使用了几个扫描仪语句。首先我阅读“地址”,然后阅读“手机号码”。然后是用户的一些随机内容。
当我使用adress=sc.next()
它从用户(没有空格)读取地址的字符串值并转到下一个扫描语句,即mobile=sc.nextBigInteger()
。通过使用此方法,我无法读取“地址(字符串)”中的空格,并且将运行时错误作为 inputMismatchException 引发。
现在如果我使用adress=sc.NextLine
,程序直接跳转到mobile=sc.nextBigInteger()
.
在上述情况和以下代码中,如何读取空格作为输入。我如何保护自己免受运行时错误的影响。我在论坛上遇到过类似的问题,但没有一个是令人满意的。谢谢你。(问我是否需要有关问题的更多信息)
预期: 输入(在地址字符串中):印度普纳马哈拉施特拉邦
输出(显示功能):印度浦那马哈拉施特拉邦。
究竟发生了什么: 如果输入(在地址字符串中):pune 输出(在显示功能中):pune
如果输入(在地址字符串中):Pune india
(现在只要我输入字符串并在那里按回车,我就会得到一个运行时错误作为 inputmismatchexception )
> JAVA
public class Data {
Scanner sc = new Scanner(System.in);
String adress;
BigInteger AcNo;
BigInteger mobile;
String ifsc;
void getData() {
System.out.println("Welcome to Bank System");
System.out.println("Please Enter the adress :");
adress= sc.next();
System.out.println("Enter the Mobile Number");
mobile = sc.nextBigInteger();
System.out.println("Enter the Account Number");
AcNo = sc.nextBigInteger();
System.out.println("Enter the IFSC Code");
ifsc= sc.next();
}
public static void main(String[] args) {
Data d=new Data();
d.getData();
}
}
解决方案
改变这一行;
adress= sc.next();
用这条线;
adress = sc.nextLine();
这将解决您的问题。scan.nextLine()
返回所有内容,直到下一个新行delimiter
,或者\n
,但scan.next()
不是。
所以所有的代码都是这样的;
public class Data{
String adress;
BigInteger AcNo;
BigInteger mobile;
String ifsc;
void getData() {
System.out.println("Welcome to Bank System");
System.out.println("Please Enter the adress :");
adress = new Scanner(System.in).nextLine();
System.out.println("Enter the Mobile Number");
mobile = new Scanner(System.in).nextBigInteger();
System.out.println("Enter the Account Number");
AcNo = new Scanner(System.in).nextBigInteger();
System.out.println("Enter the IFSC Code");
ifsc = new Scanner(System.in).next();
}
public static void main(String[] args) {
Data d = new Data();
d.getData();
}
}
推荐阅读
- vue.js - 如何仅将 /parent url 重定向到 /target url 而不将 /parent/child url 重定向到 /target/child?
- javascript - 使用 Javascript 更改导航栏的宽度时无法添加过渡
- nginx - 在 Nginx 中重写 URL
- python - 为什么当有条件阻止它时会发生这种情况
- c - 为什么这段代码每次都冻结?
- javascript - 如何读取存在于 Wordpress 元素中的值并在脚本中使用它?
- flutter - Flutter:如何更改同级小部件的状态?
- android - 在 viewModelScope 中抛出异常,但在它之外捕获它
- f# - 在 F# 中流式传输服务器发送的事件 (SSE)
- python - 如何使用 Celery 获取计划任务列表及其参数?