I am trying to create a Java program that reads in a set of shipments (using Scanner and a while loop), breaking if shipment number is -1 and then rejects and prints each rejected shipment along with an error message if weight is negative or zero or greater than 70 pounds, or if volume is negative or zero or greater than 1000 cubic inches.
I am receiving the following error message when compiling:
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)
I am not sure what I am doing wrong, here is the code I have now:
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");
}
}