使用扫描仪读取数据时出现异常

时间:2018-04-07 13:31:03

标签: java

我在尝试运行时遇到以下异常。我正在使用在线编译器。甚至在读取字符串后尝试使用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     线程“main”中的异常java.util.NoSuchElementException:找不到行     at java.util.Scanner.nextLine(Scanner.java:1585)     在Main.main(Main.java:12)

1 个答案:

答案 0 :(得分:0)

尝试这个

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

    }
}