473,403 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Exception in thread "main" java.util.NoSuchElementException

Each time I run the ProgTwo program, it displays:

1. Display one product
2. Display all products
3. Add a new CD
6. Exit

Enter your choice: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ProgTwo.main(ProgTwo.java:31)

What exactly does "Exception in thread "main" java.util.NoSuchElementException" mean and how can I fix it so my program runs properly?

Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.text.NumberFormat;
  3.  
  4. public class Product
  5. {
  6.    private String name;
  7.     private double price;
  8.     private int idNum;
  9.     private int quantity;
  10.  
  11.     public Product (int id, String title, double cost, int total) 
  12.     {
  13.         id = idNum;
  14.         name = title;
  15.         price = cost;
  16.         quantity = total;
  17.     }
  18.  
  19.    //-----------------------------------------------------------------
  20.    //  Returns the product's ID number.
  21.    //-----------------------------------------------------------------
  22.  
  23.     public int getID()
  24.     {
  25.        return idNum;
  26.     }
  27.  
  28.    //-----------------------------------------------------------------
  29.    //  Returns the product's name.
  30.    //-----------------------------------------------------------------
  31.  
  32.     public String getName()
  33.     {
  34.        return name;
  35.     }
  36.  
  37.  
  38.    //-----------------------------------------------------------------
  39.    //  Returns the product's price.
  40.    //-----------------------------------------------------------------
  41.  
  42.     public double getPrice()
  43.     {
  44.        return price;
  45.     }
  46.  
  47.    //-----------------------------------------------------------------
  48.    //  Returns the quantity in inventory.
  49.    //-----------------------------------------------------------------
  50.  
  51.     public int getQuantity()
  52.     {
  53.        return quantity;
  54.     }
  55.  
  56.    //-----------------------------------------------------------------
  57.    //  Returns a printablle version of the product object.
  58.    //-----------------------------------------------------------------
  59.  
  60.    public String toString()
  61.    {
  62.       NumberFormat fmt = NumberFormat.getCurrencyInstance();
  63.  
  64.       String description;
  65.  
  66.       description = fmt.format(price) + "\t" + quantity + "\t";
  67.       description += idNum + "\t" + name;
  68.  
  69.       return description;  
  70.    }
  71. }
Expand|Select|Wrap|Line Numbers
  1. import java.text.NumberFormat;
  2.  
  3. public class ProductCollection
  4. {
  5.    private Product[] collection;
  6.    private int count;
  7.     private double totalCost;
  8.  
  9.    //-----------------------------------------------------------------
  10.    //  Constructor: Creates an initially empty collection.
  11.    //-----------------------------------------------------------------
  12.    public ProductCollection ()
  13.    {
  14.       collection = new Product[100];
  15.       count = 0;
  16.         totalCost = 0.0;
  17.    }
  18.  
  19.    //-----------------------------------------------------------------
  20.    //  Adds a product to the collection.
  21.    //-----------------------------------------------------------------
  22.  
  23.    public void addProduct (int prodID, String prodName, double unitPrice, int prodQty)
  24.    {
  25.       if (count == collection.length)
  26.          increaseSize();
  27.  
  28.       int index = findProduct(prodID);
  29.  
  30.       if (index == -1)
  31.       {
  32.           collection[count] = new Product (prodID, prodName, unitPrice, prodQty);
  33.           totalCost += unitPrice;
  34.           count++;
  35.       }
  36.       else
  37.           System.out.println("Product was not added, a product having the ID number " + prodID 
  38.                             + " was found.");
  39.    }
  40.  
  41.    //-----------------------------------------------------------------
  42.    //  Increases the size of the product to the collection.
  43.    //-----------------------------------------------------------------
  44.  
  45.     private void increaseSize ()
  46.    {
  47.       Product[] temp = new Product[collection.length * 2];
  48.  
  49.       for (int prod = 0; prod < collection.length; prod++)
  50.          temp[prod] = collection[prod];
  51.  
  52.       collection = temp;
  53.     }
  54.  
  55.    //-----------------------------------------------------------------
  56.    //  Finds product from collection.
  57.    //-----------------------------------------------------------------
  58.  
  59.     public int findProduct(int prodID)
  60.    {
  61.        int index = -1;
  62.       for (int i = 0; i < count; i++)
  63.       if (collection[i].getID() == prodID)
  64.           index = i;
  65.       return index;
  66.     }
  67.  
  68.    //-----------------------------------------------------------------
  69.    //  Deletes product from the collection.
  70.    //-----------------------------------------------------------------
  71.  
  72.     public void deleteProduct(int prodID)
  73.     {
  74.        int index = findProduct(prodID);
  75.  
  76.         if (index > -1)
  77.       {
  78.             for (int i = index; i < count; i++)
  79.            {
  80.                collection[i] = collection[i+1];
  81.                count--;
  82.             }
  83.         }
  84.         else System.out.println("A product having the ID number " + prodID 
  85.                             + " was not found.");
  86.     }
  87.  
  88.    //-----------------------------------------------------------------
  89.    //  Displays product from the collection.
  90.    //-----------------------------------------------------------------
  91.  
  92.     public void displayProduct(int prodID)
  93.     {
  94.       int index = findProduct(prodID);
  95.       if (index > -1)
  96.          System.out.println(collection[index]);
  97.       else
  98.          System.out.println("A product having the ID number " + prodID 
  99.                             + " was not found.");    
  100.     }
  101.  
  102.    //-----------------------------------------------------------------
  103.    //  Returns a report describing the Product collection.
  104.    //-----------------------------------------------------------------
  105.  
  106.        public String createOutputFile()
  107.    {
  108.       String data = "";
  109.       for (int i = 0; i < count; i++)
  110.       {
  111.           data += collection[i].getID() + ",";
  112.           data += collection[i].getName() + ",";
  113.           data += collection[i].getPrice() + ",";
  114.           data += collection[i].getQuantity() + ",\n";
  115.       }
  116.       return data;
  117.    }
  118.  
  119.    public String toString()
  120.    {
  121.       NumberFormat fmt = NumberFormat.getCurrencyInstance();
  122.  
  123.       String report = "-------------------------------------------\n";
  124.       report += "My Product Collection\n\n";
  125.  
  126.       report += "Number of products: " + count + "\n";
  127.       report += "Total cost: " + fmt.format(totalCost) + "\n";
  128.       report += "Average cost: " + fmt.format(totalCost/count);
  129.  
  130.       report += "\n\nCD List:\n\n";
  131.  
  132.       for (int cd = 0; cd < count; cd++)
  133.          report += collection[cd].toString() + "\n";
  134.  
  135.       return report;
  136.    }
  137.  
  138. }
  139.  
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.io.*;
  3.  
  4. public class ProgTwo
  5. {
  6.    public static void main (String[] args) throws FileNotFoundException, IOException
  7.    {
  8.       Scanner scan = new Scanner(new File("productin.txt"));
  9.       ProductCollection data = new ProductCollection ();
  10.       String name = null;
  11.       double price = 0.0;
  12.       int idNum = 0, quantity = 0, input = 0;
  13.  
  14.         while (scan.hasNextLine())
  15.       {
  16.          scan.useDelimiter(",");
  17.             idNum = scan.nextInt();
  18.          name = scan.next();
  19.          price = scan.nextDouble();
  20.          quantity = scan.nextInt();
  21.          scan.nextLine();
  22.          data.addProduct (idNum, name, price, quantity);
  23.       }
  24.          do
  25.          { 
  26.               System.out.println("1. Display one product");
  27.                System.out.println("2. Display all products");
  28.             System.out.println("3. Add a new product");
  29.             System.out.println("6.  Exit");
  30.             System.out.print("\nEnter your choice: ");
  31.             input = scan.nextInt();
  32.  
  33.             switch (input)
  34.             {
  35.         case 1:  System.out.print("Enter the ID number of the product to display: " );
  36.                                      idNum = scan.nextInt();
  37.                                      data.displayProduct(idNum);
  38.              break; 
  39.         case 2:  System.out.println (data);
  40.                      break; 
  41.                         case 3:  System.out.print("Enter the ID number: ");                                
  42.                         idNum =scan.nextInt();
  43.                         System.out.print("Enter the name: " );
  44.                         name = scan.nextLine();
  45.                         System.out.print("Enter the price: " );
  46.                         price = scan.nextDouble();
  47.                         System.out.print("Enter the quantity: ");
  48.                         quantity = scan.nextInt();
  49.                         data.addProduct(idNum, name, price, quantity);
  50.                         System.out.println(data);                   
  51.                         break;
  52.             }
  53.          } while (input != 6);
  54.  
  55.       FileWriter fw = new FileWriter("productout.txt");
  56.       BufferedWriter bw = new BufferedWriter(fw);
  57.       PrintWriter pw = new PrintWriter(bw);
  58.  
  59.       pw.println(data.createOutputFile());
  60.       pw.close();
  61.     }
  62. }
Apr 16 '10 #1
6 3043
Dheeraj Joshi
1,123 Expert 1GB
How does your input looks like?

I suspect your program tries to fetch value of choice from input string, and you have not mentioned the input.

Regards
Dheeraj Joshi
Apr 16 '10 #2
The input is an integer whose value is zero. My program doesn't allow me to add any information in, it just displays the above message.
Apr 16 '10 #3
Dheeraj Joshi
1,123 Expert 1GB
Put some debug statements and display the value of all variable in ProgTwo class line number 32.

Check the output of debug statement and verify whether the input is correct on not.

Regards
Dheeraj Joshi
Apr 16 '10 #4
Pardon my ignorance, but how can I do that?
Apr 16 '10 #5
Dheeraj Joshi
1,123 Expert 1GB
Put some print statements. Basically that is just to make sure that, you are able to
fetch all the values.

If you are using some IDE like netbeans or eclipse, please debug the code and see the local variable values as scanner picks the data.

Regards
Dheeraj Joshi
Apr 16 '10 #6
jkmyoung
2,057 Expert 2GB
Ah! You're using the same scanner that you used on the file to try and get user output, correct? Of course it throws an error, because we're already done reading the file; but that's not where you want to read from.

Create a new scanner:
Expand|Select|Wrap|Line Numbers
  1. Scanner userInput = new Scanner(System.in)
  2. ...
  3. System.out.print("\nEnter your choice: "); 
  4. input = userInput.nextInt(); 
Apr 16 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Phillip Montgomery | last post by:
Hello all; I'm trying to debug an issue with a java script called, SelectSockets. It appears to be a fairly common one found on the web. I downloaded the SGI Java v1.4.1 installation from SGI's...
1
by: Andy Howells | last post by:
Can anybody help me on this? I am getting the below error but have not got a clue why. The file in my classpath eing used has the class that it says is not defined. Any ideas? I am running java...
1
by: GHKASHYAP | last post by:
Hi this is the exception i am getting when i am trying to run this application: Exception in thread "main" java.lang.NullPointerException thanks in advance.. package...
3
by: Ananthu | last post by:
Hi This is my codings in order to access mysql database from java. Codings: import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement;
4
by: HaifaCarina | last post by:
here's the complete lines of errors.. Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:332) at...
9
by: tiyaramunna | last post by:
I am trying to configure my system with Java program just to practice on the coding....when i compile a test.java program i am able to see the class file but i cant run the program ... I am getting...
4
by: jmitch89 | last post by:
I don't why I get this error: Exception in thread "main" java.lang.NoClassDefFoundError The statement below works just fine: java -cp...
1
by: jimgym1989 | last post by:
I dont get it..why is the error: Exception in thread "main" java.util.InputMismatchException this is my code /** * @(#)textFileRead.java * * * @author * @version 1.00 2008/10/17 */
3
by: ohadr | last post by:
hi, i get Exception in thread "main" java.lang.NullPointerException when i run my application. the exact error is: "Exception in thread "main" java.lang.NullPointerException at...
1
by: onlinegear | last post by:
HI i am writing this for college i know i have loads of combo boxes with nothing in the i havent got that far yet. but every time i run this is comes up with this erro run: Exception in thread...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.