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.
Related
This is the description of the problem and here is the code that I got:
PP 10.1 Design and implement a program that reads a series of 10 inte- gers from
the user and prints their average. Read each input value as a string, and then
attempt to convert it to an integer using the Integer.parseInt method. If this process
throws a NumberFormatException (meaning that the input is not a valid number),
print an appropriate error message and prompt for the number again. Continue
reading values until 10 valid integers have been entered.
This is the code I have so far:
import java.util.Scanner;
public class average
{
private int number_values;
private int[] int_values;
private double average;
public average(int number_values)
{
this.number_values = number_values;
}
public void values()
{
String value_string = null;
int int_value = 0,a;
Scanner number = null;
a = 0;
int_values = new int [number_values];
while (a < number_values)
{
try{
number = new Scanner(System.in);
System.out.print("Please enter a value:");
value_string = number.nextLine();
int_value = Integer.parseInt(value_string);
int_values[a++] = int_value;
}
catch (NumberFormatException ex)
{
System.out.print("This is an invalid input. Please renter another number:");
continue;
}
}
}
public void printValues()
{
System.out.println("The values are:");
for (int a = 0; a < number_values; a++)
{
System.out.println("Number - " + (a + 1) + " = " + int_values);
}
}
public double get_average()
{
int sum = 0;
for(int a = 0; a < number_values; a++)
{
sum += int_values[a];
}
average = (double) sum / number_values;
return (average);
}
public static void main(String[] args)
{
average a = new average(10);
a.values();
a.printValues();
System.out.println("Average = " + a.get_average());
}
}
When I enter an incorrect character it says "This is an invalid input. Please renter another number:Please enter a value:"
And when I displays the average it says Number - 1 = [I#330bedb4" for all of the values.
So the println string when I enter a incorrect input is messed up and the values are messed up. What am I missing?
Try intValues[i], if you want to output a specific item of your array. Otherwise you get the toString representation of the array object itself.
And please next time post your code instread of screenshots ;)
You're not printing the elements of the array. You're printing the array string representation directly. The error is done in your printValues() method.
To solve this, you must call an element of the array. In this case, you want to call all elements, so you must use a loop. Here:
public void printValues()
{
System.out.println("The values are:");
for (int a = 0; a < number_values; a++)
{
System.out.println("Number - " + (a + 1) + " = " + int_values[i]);
}
}
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.
In my current assignment, I have a text file that contains a large number of words which is stored in a List. one of my methods must store all words of a certain (user specified) length from this List into a Set. furthermore, the different lists are placed into two different classes. My question is: How do I retrieve the length of Individual elements in that list? EDIT: here are the complete classes.
File and List are set up like this in the client class, HangmanMain:
// Class HangmanMain is the driver program for the Hangman program. It reads a
// dictionary of words to be used during the game and then plays a game with
// the user. This is a cheating version of hangman that delays picking a word
// to keep its options open. You can change the setting for SHOW_COUNT to see
// how many options are still left on each turn.
import java.util.*;
import java.io.*;
public class HangmanMain {
public static final String DICTIONARY_FILE = "E:/CSC143/Workspace/Assignment2/src/dictionary.txt";
public static final boolean DEBUG = false; // show words left
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome to the cse143 hangman game.");
System.out.println();
// open the dictionary file and read dictionary into an ArrayList
Scanner input = new Scanner(new File(DICTIONARY_FILE));
List<String> dictionary = new ArrayList<String>();
while (input.hasNext()) {
dictionary.add(input.next().toLowerCase());
}
// set basic parameters
Scanner console = new Scanner(System.in);
System.out.print("What length word do you want to use? ");
int length = console.nextInt();
System.out.print("How many wrong answers allowed? ");
int max = console.nextInt();
System.out.println();
// set up the HangmanManager and start the game
List<String> dictionary2 = Collections.unmodifiableList(dictionary);
HangmanManager hangman = new HangmanManager(dictionary2, length, max);
if (hangman.words().isEmpty()) {
System.out.println("No words of that length in the dictionary.");
} else {
playGame(console, hangman);
showResults(hangman);
}
}
// Plays one game with the user
public static void playGame(Scanner console, HangmanManager hangman) {
while (hangman.guessesLeft() > 0 && hangman.pattern().contains("-")) {
System.out.println("guesses : " + hangman.guessesLeft());
if (DEBUG) {
System.out.println(hangman.words().size() + " words left: "+ hangman.words());
}
System.out.println("guessed : " + hangman.guesses());
System.out.println("current : " + hangman.pattern());
System.out.print("Your guess? ");
char ch = console.next().toLowerCase().charAt(0);
if (hangman.guesses().contains(ch)) {
System.out.println("You already guessed that");
} else {
int count = hangman.record(ch);
if (count == 0) {
System.out.println("Sorry, there are no " + ch + "'s");
} else if (count == 1) {
System.out.println("Yes, there is one " + ch);
} else {
System.out.println("Yes, there are " + count + " " + ch+ "'s");
}
}
System.out.println();
}
}
// reports the results of the game, including showing the answer
public static void showResults(HangmanManager hangman) {
// if the game is over, the answer is the first word in the list
// of words, so we use an iterator to get it
String answer = hangman.words().iterator().next();
System.out.println("answer = " + answer);
if (hangman.guessesLeft() > 0) {
System.out.println("You beat me");
} else {
System.out.println("Sorry, you lose");
}
}
}
my method is set up as such in the HangmanManager class.
import java.util.*;
import java.io.*;
public class HangmanManager {
private List<String> dictionary;
private int length;
private int max;
private Set<String> w = new HashSet<String>();
private SortedSet<Character> guess;
Integer L1 = new Integer(length);
public HangmanManager (List<String> dictionary, int length, int max){
this.dictionary = dictionary;
this.length = length;
this.max = max;
}
public Set<String> words (){
while (scan.hasNext()){
if (scan.next().equals(L1)){
w.add(scan.next());
}
}
return w;
}
public int guessesLeft(){
return max;
}
public SortedSet <Character> guesses(){
Scanner input = new Scanner (System.in);
return guess;
}
public String pattern(){
return null;
}
public int record (char guess){
return guess;
}
}
the Scan is just a placeholder name. As you can see in the first block, the while loop adds all the strings in the DICTIONARY_FILE in the "dictionary" list. What I want to do in the second block is add all the words of a certain length into the w list but I don't know how to read the file from a completely different class (if that's even possible) and I also don't know how to take the length of each individual element in said file. do you guys have any ideas? or do you need me to upload more info.
PS: the full title of my assignment is "Evil Hangman." From what I've looked up, its a fairly common programming assignment so you should be able to google it and get more info on what I mean.
PSS: don't mind the other methods in HangmanManager. I'm mostly focused on the "Words" method.
Thanks for the help.
Okay, so assuming you have the list with all the words set up, here is some pseudocode to guide you forwards.
for every string in set
check if word is of specified length
if true:
add word to set
if false:
do nothing
String api might have some useful methods for this, especially for determining the length of the string.. :)
About the latter part of your question, it is somewhat hard to answer how to access things in another class without more code to see how it is set up. Generally, you use a getter method to retrieve the field.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a csv file that has a list with student id's, lastname, firstname, marks, phone number, etc. I have organized them into an array list so when you call stu[100].mark it will find the mark of the 100th student on the list of the csv file. There are 1000 students. I need to calculate the total overall average mark for all the students (each student only has one mark) I have put it in a loop, but it just prints out their mark. If you need more details, than I apologize.
Here is the code:
public class StudentRecs {
public static String user;
public int StuRec;
public static int numstu;
public static double average;
//public static StuRec[] stu;
static StuRec[] stu = new StuRec[1000];
public static void main(String[] args) throws IOException {
for (int i = 0; i < 1000; i++) {
stu[i] = new StuRec();
}
StuRec stu = new StuRec();
readFile(user);
menu();
}
public static String filename;
Scanner reader = new Scanner(filename);
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() {
int total = 0;
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");
choice = userInput.nextLine();
for (int i = 0; i < numstu; i++) {
if (choice.equalsIgnoreCase("L")) {
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")){
} else if (choice.equalsIgnoreCase("AA")) {
total = total + stu[i].mark;
} else {
System.err.println("Unknown Key Try Again...");
}
average = total / 1000; // compute the average.
System.out.println(average);
} return menu();
}
}
Your average routine is computing incorrectly. It's simply taking the n'th mark and adding it to itself, divided by 1000. Since you're using integers, it will just round down, effectively giving you n'th mark + 0 for average on each iteration, leaving you with the last mark on the loop completion.
You need to keep adding to average, and divide by 1000 when you are done to get the value.
public static boolean menu() {
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");
choice = userInput.nextLine();
for (int i = 0; i < numstu; i++) {
if (choice.equalsIgnoreCase("L")) {
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")){
} else if (choice.equalsIgnoreCase("AA")) {
average += stu[i].mark; // keep adding to average
} else {
System.err.println("Unknown Key Try Again...");
}
}
// divide by zero protection
if ( 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.
// might be better to use double
}
else {
System.out.println("Oops! No students! :(");
}
return menu();
}
Note that your menu is a little inefficient, but the problem at hand should be solved.
Others have already pointed out the issue with not correctly calculating the sum of the scores, the numerator of the average calculation. I want to focus on the issue of the number of scores, the denominator of the average calculation.
Think real world. As others have mentioned, you cannot depend on the number of students in the file being fixed. File/class size can vary, so you cannot divide by a fixed number.
But neither can you depend on the number of scores being the same as the number of students, so you cannot simply divide by the number of students in that file. A student might not have a mark for a particular assignment (sickness, excused absence, or whatever). A good routine will account for the possibility of blanks (as well as invalid values), and thus I would expect you to need to count the valid, non-blank marks at the same time that you total them so that you can take the appropriate quotient at the end.
This statement is the problem
average = stu[i].mark + stu[i].mark / 1000;
This does not accumulate a total. Instead try
total = total + stu[i].mark;
And then at the end, outside the loop
average = total / 1000;