The other question I asked was excellently answered, but at the end the person mentioned an issue with taking an int and not clearing to the next line in the file. I tried a few different things (the commented out stuff in my code that you will see) and nothing seems to work. I always get the same error no matter what I changed. Here is the error, my code, my class code, then the file in that order.
The error:
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.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at HuntowskiSamuel.main(HuntowskiSamuel.java:25)
The code section:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
//garbage = scan.nextLine(); //Consuming the newline character
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
int i = scanReadIn.nextInt();
garbage = scan.nextLine(); //Getting rid of the whitespace after the int is taken
for(i=i; i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
//garbage = scan.nextLine(); //Consuming the newline after the state pull
}
Candidate_Info candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
//garbage = scan.nextLine(); //Getting rid of the whitespace after the state
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
int candidatesPerState = scan.nextInt();
garbage = scan.nextLine(); //To get rid of the rest of the whitespace after the int return
for(int i = 0; i < candidatesPerState; i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[CandidateNumber].setState(StateName);
candidates[CandidateNumber].setName(scan.next());
candidates[CandidateNumber].setOffice(scan.next());
candidates[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[CandidateNumber].setVotes(scan.nextInt());
candidates[CandidateNumber].setSpent(scan.nextDouble());
candidates[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
//garbage = scan.nextLine(); //To get rid the whitespace after taking the state value
}
}
}
The class code:
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
And the file:
Illinois
3
Obama President d 131313 19.21 Great in 2008!
Daley Mayor d 5678 89000.45 My dad was good!
Stevenson Governor d 2367 43877.45 My hair is bad!
Wisconsin
6
Smith Mayor r 3 5.98 You can count on me daily!
Bush President r 11004 1222888.44 My dad was good too!
Gore President d 11003 54.34 Hear my Gore-y details!
Kim Governor r 111 3212.16 I'm the other Guy!
Hanrath Instructor i 6 0.12 What, me worry?
Jones Instructor o 9 14.56 You'd better worry!
Alaska
4
Nader President o 2 50.00 Nader's Raiders!
Alexander Mayor i 13 13.13 What am I doing?
Thompson Governor o 1 0.00 And you thought I was gone!
Schwarzenegger President o 123 1233377.94 I'll be back!
Delaware
2
Allen Instructor i 147 16.71 No exams in cs105!
Stewart President o 3 27367.67 I'm a good thing!
END_OF_FILE
Each of the data values of the file is seperated by a tab, but I didn't think that would matter as the methods that I use stop at the whitespace. Was I wrong? Where did I screw up? This is all happening at run time by the way. It compiles fine after you guys helped me earlier.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I wish to limit the input of an integer value, between certain values using a while loop, with a couple of if-else if-else statements inside it! It's kinda working, but not exactly as it should... thought of using a switch as well, but I'm too "green" to know how! If someone's up for it and knows how... I'd welcome the use of a switch as well! Even a nested switch if need be...
Here's my code:
public class OOPProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
Car Honda = new Car(2018, 20000, "Honda", "Civic", 200, 6, 0, 0);
System.out.println("Manufacturer is: " + Honda.maker + ", model: " + Honda.model +
", year of fabrication: " + Honda.year + ", price: " + Honda.price + "!");
System.out.println("Please start the engine of your vehicle, by typing in 'Yes' or 'Start' or 'Turn on'!");
System.out.print("Do you wish to start the engine?");
System.out.println(" ");
Honda.StartEngine(sc);
//System.out.println("Engine is on!");
System.out.println("Do you wish to depart? Shift in to the first gear then and accelerate!");
System.out.println("Type in the speed: ");
Honda.accelerate(sc);
System.out.println("We are departing! Shifting in to " + Honda.currentGear +
"st gear and accelerating to " + Honda.currentSpeed + " km per hour!");
}
Constructor & functions:
public class Car {
public int year;
public int price;
public String maker;
public String model;
public int maximumSpeed;
public int numberOfGears;
public int currentSpeed;
public int currentGear;
public boolean isEngineOn;
public Car(int year, int price, String maker, String model, int maximumSpeed,
int numberOfGears, int currentSpeed, int currentGear) {
this.year = year;
this.price = price;
this.maker = maker;
this.model = model;
this.maximumSpeed = maximumSpeed;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
}
public String StartEngine(Scanner in) {
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
isEngineOn = true;
System.out.println("Engine is on!");
return input;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
return null;
}
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(isEngineOn && currentSpeed > 0){
currentGear++;
} else if(currentSpeed > 50){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
It's taking the input, but it's not going further with it as it should, neither does it give an error message or stop the app, what's my mistake?
Changing the order of your if statement will work.
In your current method:
if(isEngineOn && currentSpeed > 0)
Will always return true with any value that you enter.
Using this method will get you a little further, although I suspect it will still won't be what you are expecting, but I hope it helps you in the right direction.
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(currentSpeed > 50 && currentGear <= 1){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else if(isEngineOn && currentSpeed > 0){
currentGear++;
break; /* I've added this to break out of the method to progress in your flow */
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
What I have is a two snippets of code. The question I have in particular is about my dropCourse method within the student driver. Everything in my code seems to work fine except when I drop a course it does not drop the courses credits. For example, if I drop a course named "Computer101" which had four credits, it will remove "Computer101" From the schedule, but will not remove the "4" credits when I choose option 5 to print the total credits. So if we have a full schedule of:
Computer101 in position 0 worth 4 credits
Physics105 in position 1 worth 4 credits
Art101 in position 2 worth 4 credits
Chem101 in position 3 worth 4 credits
And I decide to drop Computer101 from the schedule, all other classes will move up in their position in the array as they are supposed to, when printing the schedule that class will no longer show up and when it is searched for it will not be found, but the amount of credits it was worth will still be there. I feel like the solution is right in front of me, but I am so burned out I am not seeing it. I would really appreciate any help and I hope I was clear with what I am asking.
Here is where my dropCourse method will be found:
public class Student
{
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
final int MAX_CREDITS = 18;
int courseNumber = 0; //start out with no courses
int totalCredits;
final int SIZE = 6;
String [ ] schedule = new String [SIZE];
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
System.out.println("The course has been added!");
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 6 courses
{
System.out.println("You have exceeded 6 courses.");
}//end courseNumber
}//addCourse
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
public int searchCourse(String courseName)
{
String course;
boolean flag = false;
int index = 0;
while(index < courseNumber && flag == false)
{
String extract = schedule[index].substring(0,6);
if (extract.contains(courseName) == true)
{
flag = true;
}
else
{
index++;
}
}
if (flag == false)
{
return -1;
}
else
{
return index++;
}
}
public void dropCourse(String courseName)
{
int found;
found = searchCourse(courseName);
int index = 0;
if (found == -1)
{
System.out.println("Course not in schedule");
}
else
{
if (found == 5)
{
courseNumber = courseNumber -1;
}
else
{
for (index = found; index < courseNumber; index ++)
{
schedule[index] = schedule[index + 1];
}
courseNumber = courseNumber -1;
System.out.println("The course has been dropped!");
}
}
}
public int totalCredits()
{
System.out.println("The total credits are " + totalCredits);
return totalCredits;
}
}//end class Student
This is where my menu that works with the above code is:
//This is a Driver program to test the external Class named Student
import java.util.Scanner;
public class TheMenu //BEGIN Class Definition
{
//**************** Main Method*************************
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
//Data Definitions:
//Instance Data
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
String courseName;
int courseCredits;
int menu = 0;
//Initialize first Student
name = "Florence Welch";//look her up
id = "7777";
street = "777 Heaven Street";
city = "Witchville";
state = "NY";
zip = "12345";
major = "Arts";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
while (menu < 6)//begin while for menu options
{
System.out.println("1. Add a course ");
System.out.println("2. Search for a course");
System.out.println("3. Drop a course");
System.out.println("4. Print out a student's schedule");
System.out.println("5. Print out total credits");
System.out.println("6. Exit");
System.out.println("Enter an option: ");
menu = scan.nextInt();
if (menu == 1)//option to add course
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);//uses method to store course information in array
}
else if (menu == 2)//option to search for course
{
int x;
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
student1.searchCourse(courseName);
x = student1.searchCourse(courseName);
if (x == -1)//course is not found if value returns -1
{
System.out.println("Course not found");
}
else
{
System.out.println("Course found in position " + student1.searchCourse(courseName));//shows user the position of course
}
}
else if (menu == 3)//will drop course from users schedule
{
System.out.println("Please enter the course you wish to drop: ");
courseName = scan.next();
student1.dropCourse(courseName);
}
else if (menu == 4)//displays the users schedule
{
System.out.println(name + "'s Schedule:\n\n");
student1.displaySchedule();
}
else if (menu == 5)//will display users credits for semester
{
student1.totalCredits();
}
else
{
System.out.println("Enjoy your semester!");//option 6 will exit program
}
}
}
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
This is really odd, I wrote a class for this program and was about to test how it reads data in from the file but I'm getting a "Cannot find symbol" error that refers to the "new" in the first scanner declared. The same error for the "=" in the second Scanner variable, and a bunch of cannot find symbols for all the "Candidate_Info[i]" objects later on. I dunno where my error is. I'm using notepad++ by the way, compiling and running it using notepad++ too.
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File CFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(Cfile);
File CfileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(CFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info Candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
Candidate_Info [i] = Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
Candidate_Info[CandidateNumber].setState(StateName);
Candidate_Info[CandidateNumber].setName(scan.next());
Candidate_Info[CandidateNumber].setOffice(scan.next());
Candidate_Info[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
Candidate_Info[CandidateNumber].setVotes(scan.nextInt());
Candidate_Info[CandidateNumber].setSpent(scan.nextDouble());
Candidate_Info[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
}
}
}
And here's the code for the Class I wrote.
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
Samuel, try and use the "camelCase" naming convention where the first letter of a variable name is lowercase, not uppercase. Only classes should get uppercase first letters. That lets you easily identify whether something is a class or a variable.
Not doing this has already resulted in a small mistake in the beginning of your code, where you accidentally refer to the CFile variable as Cfile, which Java will interpret as two different things. This is why you were getting the error about not being able to find the symbol, because Java didn't know what Cfile was, only CFile.
I also took a look lower in your code. You create a candidates variable, but then accidentally keep referring to it by its class Candidate_Info in the for and while loops.
To construct a new object out of a class, you must put the new keyword before it. You cannot just directly reference the constructor method as you did in the for loop.
Here's a version that may better show what I mean:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String stateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int numberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
stateName = scanReadIn.next(); //The prime read for the while loop
int numberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(stateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
numberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
stateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info candidates [] = new Candidate_Info [numberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < numberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
stateName = scan.next(); //Prime read for the data taking loop
while(stateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int candidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[candidateNumber].setState(stateName);
candidates[candidateNumber].setName(scan.next());
candidates[candidateNumber].setOffice(scan.next());
candidates[candidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[candidateNumber].setVotes(scan.nextInt());
candidates[candidateNumber].setSpent(scan.nextDouble());
candidates[candidateNumber].setMotto(scan.nextLine());
candidateNumber++;
}
stateName = scan.next();
}
}
}
Note that without your text files, it's going to be hard to determine how your code will actually work, but I just wanted to warn you about a common problem with Scanner when you mix nextInt with nextLine. See this.
i'll get straight to the chase. If a user wants to read another file they must type r in the menu, then they are thrown with a return readFile(); method which takes them to the top of the program and asks them the same question it did at the beggining when they first ran this program. Only issue is when you type R or Default it throws an OutOFBoundsException. BTW It is Reading a CSV file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at studentrecs.StudentRecs.in(StudentRecs.java:71)
at studentrecs.StudentRecs.readFile(StudentRecs.java:55)
at studentrecs.StudentRecs.menu(StudentRecs.java:97)
at studentrecs.StudentRecs.main(StudentRecs.java:33)
Java Result: 1
/
public static Boolean readFile(String filename) throws IOException { //Constructor for filename
try {
Scanner userInput = new Scanner(System.in);
System.out.println("Type R To Read a File or Type Default for the default file");
user = userInput.nextLine();
if (user.equalsIgnoreCase("r")) {
user = userInput.nextLine();
}
filename = user;
if (user.equalsIgnoreCase("default")) {
filename = "newreg2.csv";
}
Scanner input = new Scanner(new FileReader(filename));
while (input.hasNext()) {
in(input.nextLine());
numstu++;
}
input.close();
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
return false;
}
public static void in(String reader) {
String splitter[];
splitter = reader.split(",");
stu[numstu] = new StuRec();
stu[numstu].studentID = splitter[0];
stu[numstu].lastName = splitter[1];
stu[numstu].firstName = splitter[2];
stu[numstu].phoneNumber = splitter[3];
stu[numstu].courseCode = splitter[4];
stu[numstu].periodNumber = Integer.parseInt(splitter[5]); // parseInt turns a string of digits into an integer
stu[numstu].mark = Integer.parseInt(splitter[6]);
}
public static boolean menu() throws IOException {
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
System.out.println("Type X To Exit The Program");
choice = userInput.nextLine();
double average = 0.0; // declare average
if (choice.equalsIgnoreCase("L")) {
for (int i = 0; i < numstu; i++) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}
}else if (choice.equalsIgnoreCase("R")){
return readFile(filename);
} else if (choice.equalsIgnoreCase("AA")) {
for (int i = 0; i < numstu; i++) {
average += stu[i].mark; // keep adding to average
}
}else if (choice.equalsIgnoreCase("X")) {
for (int i = 0; i < numstu; i++) {
System.exit(i);
}
}else if (choice.equalsIgnoreCase("AC")) {
} else {System.err.println("Unknown Key Try Again...");
}
// divide by zero protection
if ( choice.equalsIgnoreCase("AA") && numstu > 0 ) {
average = average/numstu; // compute the average. Always use the size in terms of a variable whenever possible.
System.out.println(average); // as noted below, if this is an integer value, < #of students computations will eval to 0.
}
else if (!choice.equalsIgnoreCase("AA") && numstu < 0) {
System.out.println("Oops! No Marks To Calculate! :(");
}
return menu();
}
}
It looks like EITHER you have initialised numstu to start at 1, OR you have more than 1000 lines in your file.
The effect of either of these errors would be that you eventually attempt to write data to entry 1000 of stu. But since you've initialised stu with 1000 entries, numbered from 0 to 999, this gives your error.
You should make sure that numstu is initially 0, not 1.
And next time you post a question, post ALL of your code, not just the parts where you think the error might be. It's very difficult for most people to find bugs in code that they can't see.
the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))