发货的Java程序

时间:2017-12-01 15:34:44

标签: java

我正在尝试创建一个读取一组货件的Java程序(使用Scanner和while循环),如果货件编号为-1则中断,然后拒绝并打印每个被拒绝的货件以及重量为的错误消息负数或零或大于70磅,或者如果体积为负或零或大于1000立方英寸。

编译时收到以下错误消息:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Shipment.main(Shipment.java:30)

我不确定我做错了什么,这是我现在的代码:

import java.util.Scanner;  
public class Main {  
    public static void main(String[] args) {  
        int shipmentNumber;  
        double shipmentWeight = 0;  
        double shipmentVolume = 0;  
        double totalWeight = 0;  
        double totalVolume = 0;  
        Scanner sc = new Scanner(System.in);  
        while(true) {  
            System.out.println("Enter shipment number: ");  
            shipmentNumber = sc.nextInt();  

            if(shipmentNumber == -1) {  
                break;  
            }  
            System.out.println("Enter shipment weight: ");  
            shipmentWeight = sc.nextDouble();  
            System.out.println("Enter shipment volume: ");  
            shipmentVolume = sc.nextDouble();  
            if(shipmentWeight <= 0 || shipmentWeight > 70) {  
                System.out.println("Shipment " + shipmentNumber + " rejected!!! Weight '" + shipmentWeight + "'pounds is invalid");  
                continue;  
            } else if (shipmentVolume <= 0 || shipmentVolume > 1000) {  
                System.out.println("Shipment " + shipmentNumber + " rejected!!! Volume '" + shipmentVolume + "'cubic inches is invalid");  
                continue;  
            } else {  
                System.out.println("Shipment " + shipmentNumber + " accepted!!!\nWeight: " + shipmentWeight + "pounds  Volume: " + shipmentVolume + "cubic inches");  
            }  

            totalWeight += shipmentWeight;  
            totalVolume += shipmentVolume;  
        }  
        System.out.println("Total shipment weight: " + totalWeight + "pounds");  
        System.out.println("Total shipment volume: " + totalVolume + "cubic inches");  
    }  
}  

2 个答案:

答案 0 :(得分:1)

从评论中,您似乎在在线编辑器/编译器中运行该程序。 大多数在线编译器不会向最终用户公开标准输入和输出。所以System.in不可用。在您的电脑中本地运行此代码,它将运行没有问题。

答案 1 :(得分:-1)

似乎输入已用尽,并且在调用nextInt()之前无法声明整数值。

请尝试按照此片段进行操作

if(sc.hasNextInt()){
    shipmentNumber = sc.nextInt();
}