【问题标题】:Exception when using scanner to read data使用扫描仪读取数据时出现异常
【发布时间】:2018-04-07 13:31:02
【问题描述】:

尝试运行此程序时出现以下异常。我正在使用在线编译器。甚至在读取字符串后尝试使用 nextLine() 但它不起作用。

    Input:
    Enter the Customer Name:Roger Clinton
    Enter the Customer id:101
    Enter Credit Limit:10000


    Expected Output
    The Customer details are
    Customer Name: Roger Clinton
    Customer id: 101
    Credit Limit: 10000.00


    public class Main {
        public static void main(String[] args) {

           Scanner sc=new Scanner(System.in); 

           System.out.println("Enter the Customer Name:");
           String name=sc.nextLine();
           sc.nextLine();
           System.out.println("Enter the Customer id");
           int id=sc.nextInt();
           System.out.println("Enter Credit Limit:");
           double bal=sc.nextDouble();
           System.out.println("The Customer details are");
           System.out.println("Customer Name:"+name);
           System.out.println("Customer id:"+id);
           System.out.println ("Credit Limit: "+String.format("%.2f", bal));

        }
    }

我得到了以下异常: 输入客户名称: 输入客户 ID 线程“主”java.util.NoSuchElementException 中的异常:找不到行 在 java.util.Scanner.nextLine(Scanner.java:1585) 在 Main.main(Main.java:12)

【问题讨论】:

  • 当你使用 next() 时会抛出异常,那么在 after 之后放置什么有帮助呢?
  • 我无法重现该错误。代码在我的机器上运行正常。
  • 为什么要制造三台扫描仪而不是使用第一台?
  • 部分在线ide不支持用户输入,请检查您的ide是否支持
  • 您的在线IDE有问题。它可以在我的 IntelliJ 机器上运行。

标签: java


【解决方案1】:

试试这个

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        System.out.println("Enter the Credit Card details");
        System.out.println("Enter the expiry month :");
        Scanner sc=new Scanner(System.in);
        int exp=sc.nextInt();
        Scanner sc1=new Scanner(System.in);
        System.out.println("Enter the card holder name :");
        String name = sc1.nextLine(); // ** i guess you had a typo here** 
        Scanner sc2=new Scanner(System.in);
        System.out.println("Enter the credit balance :");
        float bal=sc2.nextFloat();
        System.out.println("Credit Card Details");
        System.out.println("Expiry Month :"+exp);
        System.out.println("Name :"+name);
        System.out.println ("Credit Balance :"+String.format("%.2f", bal));

    }
}

【讨论】:

    猜你喜欢
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2014-02-11
    • 2017-09-04
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多