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.NoSuc hElementExcepti on
at java.util.Scann er.throwFor(Sca nner.java:838)
at java.util.Scann er.next(Scanner .java:1461)
at java.util.Scann er.nextInt(Scan ner.java:2091)
at java.util.Scann er.nextInt(Scan ner.java:2050)
at ProgTwo.main(Pr ogTwo.java:31)
What exactly does "Exception in thread "main" java.util.NoSuc hElementExcepti on" mean and how can I fix it so my program runs properly? - import java.io.*;
-
import java.text.NumberFormat;
-
-
public class Product
-
{
-
private String name;
-
private double price;
-
private int idNum;
-
private int quantity;
-
-
public Product (int id, String title, double cost, int total)
-
{
-
id = idNum;
-
name = title;
-
price = cost;
-
quantity = total;
-
}
-
-
//-----------------------------------------------------------------
-
// Returns the product's ID number.
-
//-----------------------------------------------------------------
-
-
public int getID()
-
{
-
return idNum;
-
}
-
-
//-----------------------------------------------------------------
-
// Returns the product's name.
-
//-----------------------------------------------------------------
-
-
public String getName()
-
{
-
return name;
-
}
-
-
-
//-----------------------------------------------------------------
-
// Returns the product's price.
-
//-----------------------------------------------------------------
-
-
public double getPrice()
-
{
-
return price;
-
}
-
-
//-----------------------------------------------------------------
-
// Returns the quantity in inventory.
-
//-----------------------------------------------------------------
-
-
public int getQuantity()
-
{
-
return quantity;
-
}
-
-
//-----------------------------------------------------------------
-
// Returns a printablle version of the product object.
-
//-----------------------------------------------------------------
-
-
public String toString()
-
{
-
NumberFormat fmt = NumberFormat.getCurrencyInstance();
-
-
String description;
-
-
description = fmt.format(price) + "\t" + quantity + "\t";
-
description += idNum + "\t" + name;
-
-
return description;
-
}
-
}
- import java.text.NumberFormat;
-
-
public class ProductCollection
-
{
-
private Product[] collection;
-
private int count;
-
private double totalCost;
-
-
//-----------------------------------------------------------------
-
// Constructor: Creates an initially empty collection.
-
//-----------------------------------------------------------------
-
public ProductCollection ()
-
{
-
collection = new Product[100];
-
count = 0;
-
totalCost = 0.0;
-
}
-
-
//-----------------------------------------------------------------
-
// Adds a product to the collection.
-
//-----------------------------------------------------------------
-
-
public void addProduct (int prodID, String prodName, double unitPrice, int prodQty)
-
{
-
if (count == collection.length)
-
increaseSize();
-
-
int index = findProduct(prodID);
-
-
if (index == -1)
-
{
-
collection[count] = new Product (prodID, prodName, unitPrice, prodQty);
-
totalCost += unitPrice;
-
count++;
-
}
-
else
-
System.out.println("Product was not added, a product having the ID number " + prodID
-
+ " was found.");
-
}
-
-
//-----------------------------------------------------------------
-
// Increases the size of the product to the collection.
-
//-----------------------------------------------------------------
-
-
private void increaseSize ()
-
{
-
Product[] temp = new Product[collection.length * 2];
-
-
for (int prod = 0; prod < collection.length; prod++)
-
temp[prod] = collection[prod];
-
-
collection = temp;
-
}
-
-
//-----------------------------------------------------------------
-
// Finds product from collection.
-
//-----------------------------------------------------------------
-
-
public int findProduct(int prodID)
-
{
-
int index = -1;
-
for (int i = 0; i < count; i++)
-
if (collection[i].getID() == prodID)
-
index = i;
-
return index;
-
}
-
-
//-----------------------------------------------------------------
-
// Deletes product from the collection.
-
//-----------------------------------------------------------------
-
-
public void deleteProduct(int prodID)
-
{
-
int index = findProduct(prodID);
-
-
if (index > -1)
-
{
-
for (int i = index; i < count; i++)
-
{
-
collection[i] = collection[i+1];
-
count--;
-
}
-
}
-
else System.out.println("A product having the ID number " + prodID
-
+ " was not found.");
-
}
-
-
//-----------------------------------------------------------------
-
// Displays product from the collection.
-
//-----------------------------------------------------------------
-
-
public void displayProduct(int prodID)
-
{
-
int index = findProduct(prodID);
-
if (index > -1)
-
System.out.println(collection[index]);
-
else
-
System.out.println("A product having the ID number " + prodID
-
+ " was not found.");
-
}
-
-
//-----------------------------------------------------------------
-
// Returns a report describing the Product collection.
-
//-----------------------------------------------------------------
-
-
public String createOutputFile()
-
{
-
String data = "";
-
for (int i = 0; i < count; i++)
-
{
-
data += collection[i].getID() + ",";
-
data += collection[i].getName() + ",";
-
data += collection[i].getPrice() + ",";
-
data += collection[i].getQuantity() + ",\n";
-
}
-
return data;
-
}
-
-
public String toString()
-
{
-
NumberFormat fmt = NumberFormat.getCurrencyInstance();
-
-
String report = "-------------------------------------------\n";
-
report += "My Product Collection\n\n";
-
-
report += "Number of products: " + count + "\n";
-
report += "Total cost: " + fmt.format(totalCost) + "\n";
-
report += "Average cost: " + fmt.format(totalCost/count);
-
-
report += "\n\nCD List:\n\n";
-
-
for (int cd = 0; cd < count; cd++)
-
report += collection[cd].toString() + "\n";
-
-
return report;
-
}
-
-
}
-
-
import java.util.Scanner;
-
import java.io.*;
-
-
public class ProgTwo
-
{
-
public static void main (String[] args) throws FileNotFoundException, IOException
-
{
-
Scanner scan = new Scanner(new File("productin.txt"));
-
ProductCollection data = new ProductCollection ();
-
String name = null;
-
double price = 0.0;
-
int idNum = 0, quantity = 0, input = 0;
-
-
while (scan.hasNextLine())
-
{
-
scan.useDelimiter(",");
-
idNum = scan.nextInt();
-
name = scan.next();
-
price = scan.nextDouble();
-
quantity = scan.nextInt();
-
scan.nextLine();
-
data.addProduct (idNum, name, price, quantity);
-
}
-
do
-
{
-
System.out.println("1. Display one product");
-
System.out.println("2. Display all products");
-
System.out.println("3. Add a new product");
-
System.out.println("6. Exit");
-
System.out.print("\nEnter your choice: ");
-
input = scan.nextInt();
-
-
switch (input)
-
{
-
case 1: System.out.print("Enter the ID number of the product to display: " );
-
idNum = scan.nextInt();
-
data.displayProduct(idNum);
-
break;
-
case 2: System.out.println (data);
-
break;
-
case 3: System.out.print("Enter the ID number: ");
-
idNum =scan.nextInt();
-
System.out.print("Enter the name: " );
-
name = scan.nextLine();
-
System.out.print("Enter the price: " );
-
price = scan.nextDouble();
-
System.out.print("Enter the quantity: ");
-
quantity = scan.nextInt();
-
data.addProduct(idNum, name, price, quantity);
-
System.out.println(data);
-
break;
-
}
-
} while (input != 6);
-
-
FileWriter fw = new FileWriter("productout.txt");
-
BufferedWriter bw = new BufferedWriter(fw);
-
PrintWriter pw = new PrintWriter(bw);
-
-
pw.println(data.createOutputFile());
-
pw.close();
-
}
-
}
6 3070
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
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.
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
Pardon my ignorance, but how can I do that?
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
jkmyoung 2,057
Recognized Expert Top Contributor
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: - Scanner userInput = new Scanner(System.in)
-
...
-
System.out.print("\nEnter your choice: ");
-
input = userInput.nextInt();
Sign in to post your reply or Sign up for a free account.
Similar topics |
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 webpage and installed it
using SGI's swmgr application. The installation was very straight
forward and there were no errors when I installed the package.
Then I ran /usr/java2/bin/javac SelectSockets.java to make the
SelectSockets.class file.
|
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 version 1.4.0 and
WMQ Series version 5.3 with CSD04.
Exception in thread "main" java.lang.NoClassDefFoundError:
com/ibm/mq/server/MQSESSION
at com.ibm.mq.MQSESSIONServer.getMQSESSION(MQSESSIONServer.java:67)
at...
|
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 com.inventive.StockMarketTrading;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
|
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;
|
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 CsvTest.readFile(CsvTest.java:26)
at Trial.main(Trial.java:24)
I have no idea what to change here because I don't know what is wrong..please help me out...
import java.io.*;
import java.util.*;
| |
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 the following error
Exception in thread "main" java.lang.NoClassDefFoundError: test
Caused by: java.lang.ClassNotFoundException: test
at java.net.URLClassLoader$1.run(Unknown Source)
at...
|
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 "appframework-1.0.3.jar;swing-worker-1.1.jar";CurrentStrobe.jar com.visionpro.currentstrobe.CurrentStrobeApp
However, the statement below produces the error:
java -cp "appframework-1.0.3.jar;swing-worker-1.1.jar" -jar CurrentStrobe.jar
Exception in thread "main"...
|
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
*/
|
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 sortmergejoin.MergeJoin.Field(MergeJoin.java:204)
at sortmergejoin.MergeJoin.SMJoin(MergeJoin.java:84)
at sortmergejoin.MergeJoin.<init>(MergeJoin.java:34)
at sortmergejoin.Main.main(Main.java:24)
Java Result: 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 "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1041)
at java.awt.Container.add(Container.java:365)
at orderingsystem.OrderingSystem.<init>(OrderingSystem.java:261)
at...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |