NoSuchElementException [英] NoSuchElementException

查看:51
本文介绍了NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序成功运行,但是一旦提示用户使用封装整个程序的while循环在末尾再次重新运行该程序,它将引发NoSuchElementException,尽管在该论坛上阅读了多个线程,但我无法明白为什么.任何帮助将不胜感激.

The program runs successfully, but once the prompt for the user to re-run the program again at the end using the while loop that encapsulates the entire program it throws a NoSuchElementException and despite reading several threads on this forum I can't understand why. Any help would be much appreciated.

import java.util.Scanner;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;

public class billingStatement {

public static void main(String[] args) {
    String again="y";
    while (again.equalsIgnoreCase("y"))
    {
        //Declare Variables
        String userName="", dateIn="";
        int month=0, date=0, year=0;

        // Billing Statement Header
        System.out.println("Southwest Power and Light");
        System.out.println("Billing Statement");

        //Date, Create Template, Print Result
        Date now = new Date();              
        SimpleDateFormat todaysDate = new SimpleDateFormat("MM/dd/yyyy");
        System.out.println("\n"+"Date: " + todaysDate.format(now));

        //Initialize Scanner
        Scanner scan = new Scanner(System.in);

        boolean validName = false;
        while (validName!= true)
        {
            System.out.print("Please enter your name (Last, First): ");
            try
            {
                userName = scan.nextLine();
                validName = true;
            }
            catch (Exception invalidName)
            {
                int loopCount=0;
                loopCount++;
                System.out.println("Unexpected input type. Please enter a valid name.");
                if (loopCount==2) validName = true;
            }
        }

        // Loop prompt until input's valid
        boolean validDate = false;
        while (!validDate)
        {
            try
            {
                System.out.print("Meter reading date (mm/dd/yyyy): ");
                dateIn = scan.nextLine();               
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                sdf.setLenient(false);
                sdf.parse(dateIn);
                validDate = true;
            }
            catch (Exception invalidDate)
            {
                System.out.println("Unexpected input. Please enter a valid date.");
            }
        }

        // Use Delimiter
        Scanner scanDate = new Scanner(dateIn);
        scanDate.useDelimiter("/");
        month = scanDate.nextInt();
        date = scanDate.nextInt();
        year = scanDate.nextInt();
        scanDate.close();

        //Meter Reading User Input
        double powerUsed = 0;
        boolean validDouble = false;
        while (!validDouble)
        {
            try
            {
                Scanner scanD = new Scanner(System.in);
                System.out.print("Electricity used (KW): ");
                powerUsed = scanD.nextDouble();
                validDouble = true;
                scanD.close();
            }
            catch (Exception invalidDouble)
            {
                int loopCount=0;
                loopCount++;
                System.out.println("Unexpected input. Please enter a valid number.");
                if (loopCount==2) validDouble = true;
            }
        }

        //Calculate base rate via Meter Read Date
        double baseRate = 0;
        switch (month)
        {
            case 1: //January
                baseRate=0.10;break;
            case 2: //February
                baseRate=0.10;break;
            case 3: //March
                baseRate=0.12;break;
            case 4: //April
                baseRate=0.12;break;
            case 5: //May
                baseRate=0.12;break;
            case 6: //June
                baseRate=0.15;break;
            case 7: //July
                baseRate=0.15;break;
            case 8: //August
                baseRate=0.15;break;
            case 9: //September
                baseRate=0.15;break;
            case 10: //October
                baseRate=0.15;break;
            case 11: //November
                baseRate=0.15;break;
            case 12: //December
                baseRate=0.10;break;
        }

        //Currency Format
        NumberFormat currency = NumberFormat.getCurrencyInstance();

        double totalCharge = 0;
        double baseLineCharge = 0;
        double baseCharge = (baseRate*powerUsed);           
        if(powerUsed<350)
        {
            baseLineCharge = powerUsed*baseRate;
        }
        if(powerUsed>350)
        {
            baseLineCharge = 350*baseRate;
        }       
        //Calculate Total Monthly Charge for Power>350 KW
        if (powerUsed<350)
        {
            totalCharge = baseCharge;
        }
        //Calculate Total Monthly Charge for 500 KW>Power>350 KW
        if (powerUsed>350 & powerUsed<500)
        {
            totalCharge = ((baseRate*350)+((powerUsed-350)*(baseRate*1.10)));
        }
        //Calculate Total Monthly Charge for Power>500 KW
        if (powerUsed>500)
        {
            double pieceChargeOne = (baseRate*350);
            //System.out.println(currency.format(pieceChargeOne));
            double pieceChargeTwo = ((150)*(baseRate*1.10));
            //System.out.println(currency.format(pieceChargeTwo));
            double pieceChargeThree = ((powerUsed-500)*(baseRate*1.25));
            //System.out.println(currency.format(pieceChargeThree));
            totalCharge = pieceChargeOne+pieceChargeTwo+pieceChargeThree;               
        }               

        //Print Output
        System.out.println("\nName: "+ userName);
        System.out.println("Meter Reading Date: " + month + "/" + date + "/" + year);
        System.out.println("Electricity Used (KW): "+ powerUsed);

        System.out.println("Baseline Charge: "+ currency.format(baseLineCharge));
        //System.out.println("Over base Charge: "+currency.format(((powerUsed-350)*(baseRate*1.10))));
        System.out.println("Total Amount Due: "+ currency.format(totalCharge));

        // Prompt user for calculating another bill
        Scanner scanAgain = new Scanner(System.in);
        System.out.print("Calculate another bill (y/n)? ");
        again = scanAgain.nextLine();

        scanAgain.close();
        scan.close();
    }
}   

}

这是创建NoSuchElementException的块.scanAgain扫描仪不会在其上方的System.out.print行中读取.悲伤的一天.

This is the block that creates the NoSuchElementException. The scanAgain scanner won't read in the System.out.print line above it. Sad day.

        // Prompt user for calculating another bill
        Scanner scanAgain = new Scanner(System.in);
        System.out.print("Calculate another bill (y/n)? ");
        again = scanAgain.nextLine();

        scanAgain.close();
        scan.close();
    }
}   

}

例外

Exception in thread "main" java.util.NoSuchElementException:
No line found at java.util.Scanner.nextLine(Unknown Source) at 
billingStatement.main(billingStatement.java:173) –

推荐答案

关闭(例如 scanDate.close(); ), Scanner 关闭基础流( System.in ).如果尚未完成从流中读取的操作,则不应这样做.

Closing (e.g. scanDate.close();) the Scanner closes the underlying stream (System.in) also. You should not do that when you are not yet done with reading from the stream.

这篇关于NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆