将String中的空格作为输入读取而不使用NextLine

问题描述 投票:1回答:1

描述:

我在下面的代码中使用了几个扫描器语句首先,我阅读“地址”,然后阅读“手机号码”然后来自用户的一些随机的东西。

当我使用adress=sc.next()

它从用户读取地址的字符串值(没有空格)并转到下一个扫描语句,即mobile=sc.nextBigInteger()。通过使用此方法,我无法读取“adress(string)”中的空格,并将抛出运行时错误作为inputMismatchException。

现在,如果我使用qazxsw poi,该程序直接跳转到qazxsw poi。

在上述情况和下面的代码中如何读取空格作为输入。我如何保护自己免受运行时错误的影响。我在论坛上遇到了类似的问题,但没有一个问题令人满意。谢谢。 (如果您需要有关问题的更多信息,请询问我)

预期:输入(在地址字符串中):pune maharashtra india

输出(显示功能):pune maharashtra india。

究竟发生了什么:如果输入(在地址字符串中):pune输出(在显示功能中):pune

如果输入(在地址字符串中):Pune india (现在,当我输入字符串并点击输入后,我得到一个运行时错误作为inputmismatchexception)

adress=sc.NextLine
java exception java.util.scanner spaces inputmismatchexception
1个回答
0
投票

改变这一行;

mobile=sc.nextBigInteger()

用这条线;

> 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
© www.soinside.com 2019 - 2024. All rights reserved.