首页 > 解决方案 > 在不使用 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();
          }
        }

标签: javaexceptionjava.util.scannerspacesinputmismatchexception

解决方案


改变这一行;

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

推荐阅读