This is my code for printing a shopping list. It works fine when I put the data manually at runtime through keyboard. But when I direct an input.txt file as an argument in command line it throws NoSuchElementException after 1st iteration.
I think it might have to do with the sequence of using Scanner.next() and Scanner.nextInt() but not sure.
How do I fix this?
import java.io.*;
import java.util.*;
class Product
{
Scanner sc = new Scanner(System.in);
int productID;
String productName;
String productType;
float productPrice;
Product()
{
// Do Nothing.
}
void createProduct()
{
System.out.println("Enter the Product ID: ");
productID = sc.nextInt();
System.out.println("Enter the Product Name: ");
productName = sc.next();
System.out.println("Enter the Product Type: ");
productType = sc.next();
System.out.println("Enter the Product Price: ");
productPrice = sc.nextFloat();
}
Product(int pID, String pName, String pType, float pPrice)
{
productID = pID;
productName = pName;
productType = pType;
productPrice = pPrice;
}
void showIdentification()
{
System.out.println(productID + " " + productName);
}
void showDetail()
{
System.out.println(productID + " " + productName + " " + productType + " " + productPrice);
}
}
class Shop
{
int n = 10;
Product list[] = new Product[n];
void createList()
{
for(int i=0; i<n; i++)
{
System.out.println("Product No. " + (i+1));
Product o = new Product();
o.createProduct();
o.showDetail();
list[i] = o;
}
}
void viewAllProducts()
{
for(int i=0; i<n; i++)
{
list[i].showIdentification();
}
}
}
class ShopList
{
public static void main(String[] args)
{
Shop sList = new Shop();
sList.createList();
sList.viewAllProducts();
}
}
Here is the input file :-
1001 CadburyA ChocolateA 15.00
1002 CadburyB ChocolateB 16.00
1003 CadburyC ChocolateC 17.00
1004 CadburyD ChocolateD 18.00
1005 CadburyE ChocolateE 19.00
1006 CadburyF ChocolateF 20.00
1007 CadburyG ChocolateG 21.00
1008 CadburyH ChocolateH 22.00
1009 CadburyI ChocolateI 23.00
1010 CadburyJ ChocolateJ 24.00
and here is the exception I got:-
java ShopList < input.txt
Product No. 1
Enter the Product ID:
Enter the Product Name:
Enter the Product Type:
Enter the Product Price:
1001 CadburyA Chocolate 15.0
Product No. 2
Enter the Product ID:
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 Product.createProduct(ShopList.java:19)
at Shop.createList(ShopList.java:59)
at ShopList.main(ShopList.java:95)