Need Help Some With This Error And I Can't Figure It Out. The program is suppose to read the input and save it. Exception in thread "main" java.util.InputMismatchException
ÏÏ§Ï at java.util.Scanner.throwFor(Scanner.java:864)
ÏÏ§Ï at java.util.Scanner.next(Scanner.java:1485)
ÏÏ§Ï at java.util.Scanner.nextDouble(Scanner.java:2413)
ÏÏ§Ï at Driver.main(Driver.java:112)
ÏϧÏ
===================================
import java.io.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
//local constants
//local variables
String fileName = "items.txt";
Scanner scanner = null;
ItemsList itemsList = new ItemsList(5);
int i = 0;
int choice;
boolean repeat = true;
String itemName;
double price;
int qty;
scanner=new Scanner(System.in);
//****************************************************************************
//open the file and catch the exception if file not found
try
{
//create an instance of scanner
scanner = new Scanner(new File(fileName));
//read file items until end of file
while(scanner.hasNext())
{
itemName = scanner.next();
price = scanner.nextDouble();
qty=scanner.nextInt();
//Add the OneItem object to the itemList
itemsList.addItem(new OneItem(itemName, price, qty));
i++;
}
//close the file object
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
//Create an instance of Scanner class
scanner=new Scanner(System.in);
while(repeat)
{
//call menu
choice = menu();
switch(choice)
{
//Add an item to the itemsList
case 1:
System.out.println("Enter item name : ");
//read name
String name=scanner.nextLine();
System.out.println("Enter price : ");
//read string value and parse to double value
price = Double.parseDouble(scanner.nextLine());
System.out.println("Enter quantity : ");
qty=Integer.parseInt(scanner.nextLine());
//Add the OneItem to the itemsList
itemsList.addItem(new OneItem(name, price, qty));
break;
case 2:
//print the list
//print heading with specific formatter
System.out.printf("%-10s%-10s%-10s\n\n", "Item","Price","Quantity");
System.out.println(itemsList.toString());
break;
case 3:
//Terminate the program
System.out.println("Terminate the program.");
//set repeat to false
repeat=false;
break;
default:
System.out.println("Incorrect option is selected.");
break;
}
}
writeToFile(itemsList);
}
private static void writeToFile(ItemsList itemsList)
{
//Create a file name called items.txt
String filename="items.txt";
//Create a variable of Class PrintWriter
PrintWriter filewriter=null;
try
{
//create an instance of PrintWriter
filewriter=new PrintWriter(new File(filename));
//close the file writer
filewriter.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
private static int menu()
{
//Create an instance of Scanner class
Scanner keyboard=new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add item");
System.out.println("2. Display items");
System.out.println("3. Exit");
System.out.println("Enter your choice");
int choice=Integer.parseInt(keyboard.nextLine());
return choice;
}
}//end Driver class
==========================================
public class OneItem
{
//declare a variables
private String name;
private double price;
private int quantity;
//default constructor
public OneItem()
{
name = "";
price = 0;
quantity = 0;
}
//parameter constructor
public OneItem(String name, double price, int quantity)
{
this.name = name;
this.price = price;
this.quantity = quantity;
}
//toString
public String toString()
{
return String.format("%-10s%-10.2f%-10d\n", name,price,quantity);
}
}//end of the OneItem class
===========================
public class ItemsList
{
//declare variables
private OneItem items[];
private int size;
private int count;
//constructor to set items, size and count to zero
public ItemsList()
{
items = null;
size = 0;
count = 0;
}
//Parameter constructor
public ItemsList(int size)
{
items = new OneItem[size];
for (int i = 0; i < items.length; i++)
{
items[i] = new OneItem();
}
this.size = size;
count = 0;
}
//Add OneItem to the itemlist
public void addItem(OneItem item)
{
if(items.length == count)
{
resize();
items[count] = item;
count++;
}
else
{
items[count] = item;
count++;
}
}
//Resize
private void resize()
{
int oldsize = size;
count = oldsize;
int newsize = 2 * this.size;
size = newsize;
OneItem[] tempList = new OneItem[size];
for (int i = 0; i < oldsize; i++)
tempList[i] = items[i];
items = new OneItem[size];
items = tempList;
}
//getSize
public int getSize()
{
return count;
}
//toString
public String toString()
{
String description = "";
for (int i = 0; i <count; i++)
{
description += items[i].toString();
}
return description;
}
}
In the future, you need to be more clear with what the issue is. How it occurs. Error i get when entering string into purchase price is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "sdcf"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at stacktests.Driver.main(Driver.java:70)
Meaning you're not validating your input at all. Example would be:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt())
{
System.out.println("Enter an integer!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
You need to disallow string entry into a numeric variable! Only once the input has been validated do you assign it to a variable.
Cheers mate.
Related
I'm creating a program where an airport worker can input plane and flight information, after which airport users can print out the plane and flight information that was input. After running the first method startAirportPanel(), and typing 1 into the reader scanner to add plane information, I would get a null pointer exception error after the plane ID and plane capacity are entered.
outcome:
Airport panel
---------------
Choose operation:
[1] Add airplane
[2] Add flight
[x] Exit
1
Give plane ID:
GHUA-HG
Give plane capacity:
22
After typing in 22 here and pressing enter, I would get the null pointer exception.
Here is the object flights:
import java.util.ArrayList;
public class Flights {
public HashMap<String,Integer> plane = new HashMap<String,Integer>();
public HashMap<String,String> flight = new HashMap<String,String>();
public Flights(){
this.plane = plane;
this.flight = flight;
}
public void planeMap(String id, Integer capacity){
plane.put(id, capacity);
}
public void flightMap(String id, String departure, String destination){
String flight1 = departure + "-" + destination;
flight.put(id, flight1);
}
public ArrayList planeList(){
ArrayList<String> keylist = new ArrayList<String>(plane.keySet());
ArrayList<Integer> valuelist = new ArrayList<Integer>(plane.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0 ; i < keylist.size() ; i++){
newlist.add(keylist.get(i) + " (" + valuelist.get(i) + ")");
}
for(int i = 0 ; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public ArrayList flightList(){
ArrayList<String> keylist = new ArrayList<String>(flight.keySet());
ArrayList<String> valuelist = new ArrayList<String>(flight.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0; i < keylist.size(); i++){
newlist.add(keylist.get(i) + " (" + plane.containsKey(keylist.get(i)) + ") " + "(" + valuelist.get(i) + ")");
}
for(int i = 0; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public int planeInfo(String id){
if(plane.containsKey(id)){
return plane.get(id);
}
return 0;
}
}
And here is the userinterface:
import java.util.HashMap;
import java.util.Scanner;
import java.util.ArrayList;
public class UserInterface {
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
public void startFlightService(){
System.out.println("Flight service ");
System.out.println("--------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[x] Print Quit");
if(reader.equals("x")){
break;
}
if(Integer.parseInt(reader.nextLine()) == 1){
printPlane();
}
if(Integer.parseInt(reader.nextLine()) == 2){
printFlight();
}
if(Integer.parseInt(reader.nextLine()) == 3){
printPlaneInfo();
}
else continue;
}
}
public void startAirplanePanel(){
System.out.println("Airport panel");
System.out.println("---------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[x] Exit");
String input = reader.nextLine();
if(Integer.parseInt(input) == 1){
addPlane();
} if(Integer.parseInt(input) == 2){
addFlight();
}
if(input.equals("x")){
break;
}
}
}
public void addPlane(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
fly.planeMap(id,capacity);
}
public void addFlight(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String departure = reader.nextLine();
System.out.println("Give destination airport code: ");
String destination = reader.nextLine();
fly.flightMap(id,departure,destination);
}
public void printPlane(){
for(int i = 0; i < fly.planeList().size(); i++){
System.out.println(fly.planeList());
}
}
public void printFlight(){
for(int i = 0; i < fly.flightList().size(); i++){
System.out.println(fly.flightList());
}
}
public void printPlaneInfo(){
System.out.print("Give plane ID: ");
String id = reader.nextLine();
System.out.println(id + " (" + fly.planeInfo(id) + ")");
}
}
Lastly, the main class to start the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Write your main program here. Implementing your own classes will be useful.
Scanner reader = new Scanner(System.in);
Flights flightss = new Flights();
UserInterface hello = new UserInterface();
hello.startAirplanePanel();
}
}
```
This part of your constructor makes no sense:
this.fly = fly;
this.reader = reader;
the reader already is instantiated, so you just replace the current value with: the current value.
The fly, however, isn't instantiated. So, you are just setting null to null.
Whatever call you make on fly, will cause an NPE.
Remove the this.reader = reader; and change the line about fly with an actual instantiation.
EDIT:
So, your constructor should be something like:
public UserInterface(){
this.fly = new Flights();
}
I would also re-check your Flights constructor.
The part of the code that is problematic is ( in the UserInterface class ):-
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
Only fly variable type (Flights) is declared without any assignment of the Flights class object.
Fix this using the 'new' keyword for instantiation of the Flights class:-
private Flights fly = new Flights();
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
However code can be refactored in a better way as suggested by #Stultuske.
I have a program here that compiles but I cannot get it to print to the command line or a report file. Any assistance is appreciated. Here is the error that I get:
Error: Main method not found in class Township, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Press any key to continue . .
import java.util.*;
import java.io.*;
//Township class
class Township
{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
}
//Driver class
class Driver
{
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("town.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int household = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, household, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException
{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}
//main method
public static void main (String[] args) throws IOException
{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
}
EDIT
I updated the error and some code thanks to the responses.
Here is the new error that I get:
Error: Exception in thread "main" java.util.InputMismatchException at
java.base/java.util.Scanner.throwFor(Scanner.java:939) at
java.base/java.util.Scanner.next(Scanner.java:1594) at
java.base/java.util.Scanner.nextInt(Scanner.java:2258) at
java.base/java.util.Scanner.nextInt(Scanner.java:2212) at
Township.readFile(Township.java:143) at
Township.main(Township.java:20)
Code:
import java.util.*;
import java.io.*;
//Township class
public class Township{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
public static void main (String[] args) throws IOException{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
//==================================================================
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
//==================================================================
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
//==================================================================
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//==================================================================
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//==================================================================
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("bicycledata.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int households = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, households, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//==================================================================
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}//end method
}//end class
Try this:
class Township {
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles) {
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
// Rest of Township class code...
public static void main(String[] args) {
// Do things...
}
}
Take a look to this: Essentials
Every application needs one class with a main method. This class is
the entry point for the program, and is the class name passed to the
java interpreter command to run the application.
IOException is thrown to you for another reason. The answer to your question has been given.
I think you are compiling class Township which do not have main() method. You should compile Driver class because class Driver has main() method and creating the object of class Township.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
public class AutoMobile {
private static String make;
private static String model;
private static String color;
private static int year;
private static int mileage;
private static int index =300;
public AutoMobile(String make, String model, String color, int year,
int mileage, int index) {
super();
this.make = make;
this.model = model;
this.color = color;
this.year = year;
this.mileage = mileage;
this.index = index;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public static int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
class Vehicle {
static ArrayList<AutoMobile> vehicleList = new ArrayList<>();
public static final String FILENAME = "F:\\CSU\\CSC320-01 Programming 1\\Week 8\\AutoMobile.txt";
//Prints to location with proper header, but returns package and no vehicles
public static void addVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Add Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter Vehicle color: ");
String color = s.nextLine();
System.out.print("Enter Vehicle year: ");
int year = s.nextInt();
System.out.print("Enter Vehicle mileage: ");
int mileage = s.nextInt();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
AutoMobile a = new AutoMobile(make, model, color, year, mileage, index);
vehicleList.add(a);
System.out.println("Vehicle Added Successfully");
System.out.println("------------------------");
}
public static void removeVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Remove Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model) &&
a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
iterator.remove();
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Removed Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void updateVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Update Vehicle-------");
System.out.print("Enter the make of Automobile: ");
String make = s.nextLine();
System.out.print("Enter the model of Automobile: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
System.out.println("-----Vehicle found-------");
System.out.print("Enter the new make of Automobile: ");
make = s.nextLine();
System.out.print("Enter the new model of Automobile: ");
model = s.nextLine();
System.out.print("Enter the new color of Automobile: ");
String color = s.nextLine();
System.out.print("Enter the new year of Automobile: ");
int year = s.nextInt();
System.out.print("Enter the new mileage of Automobile: ");
int mileage = s.nextInt();
a1.setMake(make);
a1.setModel(model);
a1.setColor(color);
a1.setYear(year);
a1.setMileage(mileage);
a1.setIndex(index);
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Updated Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void printfile() {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
String content = "ID Make Model Color Year Mileage\n";
bw.write(content);
Iterator itr=vehicleList.iterator();
while(itr.hasNext()){
bw.write(itr.next().toString()+"\n");
}
System.out.println("Done printing");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
do {
System.out
.println("============================VEHICLE OPTIONS============================");
System.out.println("1. Add Vehicle");
System.out.println("2. Remove Vehicle");
System.out.println("3. Update Vehicle");
System.out.println("4. Print Vehicle List");
System.out.println("5. Exit");
System.out
.println("=======================================================================");
System.out.println();
Scanner s = new Scanner(System.in);
System.out.print("Enter the choice: ");
int i = s.nextInt();
s.nextLine();
switch (i) {
case 1:
addVehicle();
break;
case 2:
removeVehicle();
break;
case 3:
updateVehicle();
break;
case 4:
printfile();
break;
case 5:
System.out.println("Good Bye!!!!!");
break;
default:
System.out.println("You entered the wrong choice!!!!");
System.out.println();
}
if(i==4)
break;
System.out.println();
} while (true);
PrintWriter pw = new PrintWriter("VehicleInventory");
String text ="Index,Make,Model,Color,Year,Mileage\n";
for(AutoMobile a : vehicleList){
text+=a.getIndex()+","+a.getMake()+","+a.getModel()+","+a.getColor()+","+a.getYear()+","+a.getMileage()+"\n";
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("VehicleInventory file created succesfully");
System.out.println();
System.out.println(text);
}
}
Forgive my inexperience, but I am trying to compile a program for school that achieves the following.
private string make
private string model
private string color
private int year
private int mileage.
Your program should have appropriate methods such as:
default constructor
parameterized constructor
add a new vehicle method
list vehicle information (return string array)
remove a vehicle method
update vehicle attributes method.
All methods should include try..catch constructs. Except as noted all methods should return a success or failure message (failure message defined in catch).
Create an additional class to call your automobile class (e.g., Main or AutomobileInventory). Include a try..catch construct and print it to the console any errors.
Call automobile class with parameterized constructor (e.g., "make, model, color, year, mileage").
Then call the method to list the values. Loop through the array and print to the screen.
Call the remove vehicle method to clear the variables.
Print the return value.
Add a new vehicle.
Print the return value.
Call the list method and print the new vehicle information to the screen.
Update the vehicle.
Print the return value.
Call the listing method and print the information to the screen.
Display a message asking if the user wants to print the information to a file (Y or N).
Use a scanner to capture the response. If Y, print the file to a predefined location (e.g., C:\Temp\Autos.txt). Note: you may want to create a method to print the information in the main class.
If N, indicate that a file will not be printed.
I have the program working somewhat as i wanted, until i tried to assign index numbers to the user inputted vehicles for updating or removing at a later date. This does not return in the output, and all that is returning in the .txt file is the header, and my package listed, no vehicles. Any suggestions or help would be great!
index parameter is of primitive int data type
For int use = for comparing.
if (a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex() == index) {}
I am creating a database project in java using file handling. The program is working without compiling error. Following points are not working
File is storing only first record. (if program is running again it is overwriting file)
I want to display all records but the only first record is displaying with Exeception
Please offer suggestions..
import java.io.*;
public class Student implements Serializable
{
private int roll;
private String name; //To store name of Student
private int[] marks = new int[5]; //To store marks in 5 Subjects
private double percentage; //To store percentage
private char grade; //To store grade
public Student()
{
roll = 0;
name = "";
for(int i = 0 ; i < 5 ; i++)
marks[i] = 0;
percentage = 0;
grade = ' ';
}
public Student(int roll , String name ,int[] marks)
{
setData(roll,name,marks);
}
public void setData(int roll , String name ,int[] marks)
{
this.roll = roll;
this.name = name;
for(int i = 0 ; i < 5 ; i++)
this.marks[i] = marks[i];
cal();
}
//Function to calculate Percentage and Grade
private void cal()
{
int sum = 0;
for(int i = 0 ; i < 5 ;i++)
sum = sum + marks[i];
percentage = sum/5;
if(percentage>85)
grade = 'A';
else if(percentage > 70)
grade = 'B';
else if (percentage >55)
grade = 'C';
else if (percentage > 33)
grade = 'E';
else
grade = 'F';
}
public char getGrade() { return grade; }
public double getPercentage() { return percentage; }
#Override
public String toString()
{
string format = "Roll Number : %4d, Name : -%15s "
+ "Percentage : %4.1f Grade : %3s";
return String.format(format, roll, name, percentage, grade);
}
}
second file
import java.io.*;
public class FileOperation
{
public static void writeRecord(ObjectOutputStream outFile, Student temp)
throws IOException, ClassNotFoundException
{
outFile.writeObject(temp);
outFile.flush();
}
public static void showAllRecords(ObjectInputStream inFile)
throws IOException, ClassNotFoundException
{
Student temp = new Student();
while(inFile.readObject() != null)
{
temp = (Student)inFile.readObject();
System.out.println(temp);
}
}
}
main file
(only two options are working)
import java.util.*;
import java.io.*;
public class Project
{
static public void main(String[] args)
throws IOException,ClassNotFoundException
{
ObjectInputStream inFile;
ObjectOutputStream outFile;
outFile = new ObjectOutputStream(new FileOutputStream("info.dat"));
inFile = new ObjectInputStream(new FileInputStream("info.dat"));
Scanner var = new Scanner(System.in) ;
int roll;
String name;
int[] marks = new int[5];
int chc = 0;
Student s = new Student();
while(chc != 6)
{
System.out.print("\t\tMENU\n\n");
System.out.print("1.Add New Record\n");
System.out.print("2.View All Records\n");
System.out.print("3.Search a Record (via Roll Number) \n");
System.out.print("4.Delete a Record (via Roll Number) \n");
System.out.print("5.Search a Record (via Record Number)\n");
System.out.print("6.Exit\n");
System.out.print("Enter your choice : ");
chc = var.nextInt();
switch(chc)
{
case 1:
System.out.print("\nEnter Roll number of Student : ");
roll = var.nextInt();
System.out.print("\nEnter Name of Student : ");
name = var.next();
System.out.println("\nEnter marks in 5 subjects \n");
for(int i = 0 ; i < 5 ; i++)
{
System.out.print("Enter marks in subject " + (i+1) + " ");
marks[i] = var.nextInt();
}
s.setData(roll , name , marks );
System.out.println("\n Adding Record to file \n");
System.out.printf("Record \n " + s);
System.out.println("\n\n");
FileOperation.writeRecord(outFile,s);
System.out.println("Record Added to File\n ");
break;
case 2:
System.out.println("All records in File \n");
FileOperation.showAllRecords(inFile);
break;
default: System.out.println("Wrong choice ");
}
}
outFile.close();
inFile.close();
}
}
Your program found a ClassNotFoundException and your method only throws an IOException.
I would check your import statements to make sure you are bringing in the class for ObjectInputStream
import java.io.ObjectInputStream;
If you want to get rid of unreported exception try:
Try
public static void showAllRecords(ObjectInputStream inFile) throws IOException, ClassNotFoundException
Hey I have code for a project im trying to finish up and I keep getting array out of bounds exceptions at a certain part and would like to know how to fix it. My project is to create a reservation system using 3 classes Room,Reservation and a client class. I'm having trouble with my bookRoom class after asking for the number of guests for the room.Any help would be greatly appreciated. The exception occurs at line 57 in the reservation class. The line in question is in bold.
`
public class Reservation {
public void roomInitialization(Room[] room,int numberOfRooms,int numberOfSmokingRooms)
{
boolean smoking=true;
String[] guestName={null,null,null,null};
for (int i=0;i<numberOfRooms;i++)
{
if (i>=numberOfSmokingRooms)
smoking=false;
room[i]=new Room(smoking,false,guestName,null,i+1);
}
}
public void displayRoomsInfo(Room[] room,int numberOfRooms)
{
for (int i=0;i<numberOfRooms;i++)
{
System.out.println("Room " + room[i].getroomNumber() + "\t" +
(room[i].getsmoking()?"Smoking room":"Non-Smoking Room"));
if (room[i].getoccupied())
{
System.out.print("Phone: "+room[i].getguestPhone()+"\t");
for(int j=0;j<4;j++)
System.out.print(room[i].getguestName()[j]+"\t");
System.out.println();
}
}
}
public void bookRoom (Room[] room, int numberOfRooms)
{
displayRoomsInfo(room, numberOfRooms);
Scanner scan = new Scanner(System.in);
Scanner scans = new Scanner(System.in);
Scanner scand = new Scanner(System.in);
System.out.print("Enter a Room Number: ");
int roomNumber = scan.nextInt()-1;
if (roomNumber >=0 && roomNumber < 30){
room[roomNumber].setoccupied(true);
System.out.print("Enter a Phone Number: ");
String guestPhone = scans.nextLine();
room[roomNumber].setguestPhone(guestPhone);
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt()-1;
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++)
System.out.print("Enter guest names: ");
**guestName[guests] = scand.next();**
room[roomNumber].setguestName(guestName);
}
else
System.out.println("Enter a valid room number");
}
public void checkOut(Room[] room)
{
Scanner scan=new Scanner(System.in);
int roomNumber;
String[] nullguestName={null,null,null,null};
do
{
System.out.print("Enter the room number: ");
roomNumber=scan.nextInt()-1;
if (roomNumber>=0 && roomNumber<30)
break;
else
System.out.println("Enter a valid room number");
}while(true);
if (room[roomNumber].getoccupied())
{
room[roomNumber].setoccupied(false);
room[roomNumber].setguestPhone(null);
room[roomNumber].setguestName(nullguestName);
}
else
System.out.println("room "+(roomNumber+1)+" is already empty");
}
}
`
Code for the other classes
package hotel;
public class Room {
private boolean smoking;
private boolean occupied;
private String[] guestName=new String[4];
private String guestPhone;
private int roomNumber;
public Room (boolean smoking,boolean occupied,String[] guestName, String guestPhone,int roomNumber)
{
this.smoking=smoking;
this.occupied=occupied;
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
this.guestPhone=guestPhone;
this.roomNumber=roomNumber;
}
public void setoccupied(boolean occupied) {
this.occupied = occupied;
}
public void setsmoking(boolean smoking) {
this.smoking = smoking;
}
public void setroomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
public void setguestPhone(String guestPhone) {
this.guestPhone = guestPhone;
}
public void setguestName(String[] guestName)
{
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
}
public boolean getsmoking() {
return this.smoking;
}
public boolean getoccupied(){
return this.occupied;
}
public String getguestPhone(){
return this.guestPhone;
}
public int getroomNumber() {
return this.roomNumber;
}
public String[] getguestName()
{
String[] tempguestName=new String[4];
for (int i=0;i<4;i++)
tempguestName[i]=this.guestName[i];
return tempguestName;
}
}
package hotel;
import java.util.Scanner;
public class ReservationDemo {
public static void main(String[]args)
{
final int numberOfRooms=30, numberOfSmokingRooms=5;
Room[] room=new Room[numberOfRooms];
Reservation reservation=new Reservation();
reservation.roomInitialization(room,numberOfRooms,numberOfSmokingRooms);
int userSelection;
Scanner scan=new Scanner(System.in);
do
{
System.out.println("Press: 1-Book room\t2-checkout\t3-display all rooms\t4-exit. ");
userSelection=scan.nextInt();
switch(userSelection)
{
case 1:
reservation.bookRoom(room,numberOfRooms);
break;
case 2:
reservation.checkOut(room);
break;
case 3:
reservation.displayRoomsInfo(room,numberOfRooms);
break;
case 4:
System.exit(0);
default:
break;
}
}while (true);
}
}
There are lots of mistake in your code.
First-- Use the following code instead of your version in Reservation class
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt();
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++) {
System.out.print("Enter guest names: ");
guestName[i] = scand.next();
}
Second -- Use the following method in Room class instead of the existing one.
public void setguestName(String[] guestName)
{
for (int i=0;i<guestName.length;i++)
this.guestName[i]=guestName[i];
}
Let me know what you achieve
You are trying to index into the guests array using the variable guests which is the size of the array, you should be using the iteration counter variable i instead:
guestName[guests] = scand.next() should be guestName[i] = scand.next()