I am new to Java and working on simple task - TicTacToe console game. Today I've faced a problem that I can't proceed with the main method after do while loop. The project has two classes - Main and Field. Field is responsive for all game field updates. I'm calling Field methods in do while loop of the main method but when the result is on the loop has to be finished and the main method has to go on(it should ask if the user wants to play again). Unfortunately the programm stops after do while loop.
Here is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
private static char playerSym, compSym;
private static int Sym;
public static int playerChoice;
public static boolean result;
public static void main(String args[]) throws IOException {
Field field = new Field();
// start of the game
System.out.println("Let`s play");
System.out.println("Choose your symbol please");
System.out.println("0='O', 1='X'");
Scanner sc = new Scanner(System.in);
Sym = sc.nextInt();
while (Sym != 0 & Sym != 1) {
System.out
.println("The symbol you entered is incorrect, please repeat");
System.out.println("0='O', 1='X'");
Sym = sc.nextInt();
}
// setting player character
if (Sym == 1) {
playerSym = 'X';
compSym = 'O';
} else if (Sym == 0) {
playerSym = 'O';
compSym = 'Х';
}
System.out.println("There is a game field");
System.out.println("Please choose the cell number you`d like to fill with " + playerSym);
field.firstShowFields();
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
System.out.println("Want to play once more? Y-Yes, N-No");
char answer = (char) System.in.read();
switch (answer) {
case 'Y':
System.out.println("Restarting the game");
break;
case 'N':
System.out.println("Thank you! Bye-Bye!");
break;
default:
break;
}
}
}
public class Field {
public static final int FIELD_SIZE = 3;
// private static final char DEFAULT_CHAR=' ';
public char[][] fields;
public boolean result = true;
public char playerSym;
public Field() {
fields = new char[FIELD_SIZE][FIELD_SIZE];
}
public void firstShowFields() {
int cellValue = 1;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + cellValue + "]");
cellValue++;
}
System.out.println();
}
}
public char[][] updateFields(int choice, char sym) {
playerSym = sym;
int cellValue = 1;
int playerChoice = choice;
do {
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
if (playerChoice == cellValue) {
fields[i][j] = (char) playerSym;
} else if (fields[i][j] == (char) playerSym) {
fields[i][j] = (char) playerSym;
} else {
fields[i][j] = (char) ('0' + cellValue);
}
cellValue++;
}
}
this.checkWin(fields, playerSym);
return fields;
} while (this.checkWin(fields, playerSym) == false);
}
public void showFields(char[][] fields) {
this.fields = fields;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + fields[i][j] + "]");
}
System.out.println();
}
}
public boolean checkWin(char[][] field, char playerSym) {
char[][] checkField = field;
this.playerSym = playerSym;
// checkline
if (((checkField[0][0] == checkField[0][1]) && (checkField[0][1] == checkField[0][2]))
|| ((checkField[1][0] == checkField[1][1]) && (checkField[1][1] == checkField[1][2]))
|| ((checkField[2][0] == checkField[2][1]) && (checkField[2][1] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return true;
}
// checkraw
else if (((checkField[0][0] == checkField[1][0]) && (checkField[1][0] == checkField[2][0]))
|| ((checkField[0][1] == checkField[1][1]) && (checkField[1][1] == checkField[2][1]))
|| ((checkField[0][2] == checkField[1][2]) && (checkField[1][2] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
} // checkdiagonal
else if (((checkField[0][0] == checkField[1][1]) && (checkField[1][1] == checkField[2][2]))
|| ((checkField[0][2] == checkField[1][1]) && (checkField[1][1] == checkField[2][0]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
}
return false;
}
}
Here is an infinite loop:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
result is never updated so the while (result==false); will never fail as long as it was true the first time. You may try modifying it like below:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
result = field.checkWin(field.fields, playerSym);
} while (result==false);
Also, it is not a good practice to pass fields that are already attached to the instance to instance methods. You can remove the parameter char[][] field from the checkWin method and simply have it operate on the instance variable fields. But that's not the cause of your loop issue.
As user506 points out the only reason why it won't progress past the loop is because the boolean result is never set to true.
Why do you have 2 classes to separate the main method?
Related
I am trying to make a program that tests whether or not a password is valid or invalid. After the password is submitted, I would like to give the user a choice to re-run the program(by responding 'y'). Everything works in my code, except when y is pressed at the end, the program stops instead of starting over.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String again = "y";
//Promt user to enter input
System.out.print("Enter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("Valid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
} else {
System.out.println("Invalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
}
//Program new method
public static boolean checkPassword(String password) {
String again = "y";
while((again == "Y") || (again == "y")){
boolean checkPassword = true;
{
//Make sure password is at least 7 digits
if (password.length() < 8) {
checkPassword = false;
}
else {
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++) {
if (isDigit(password.charAt(i))) {
if(isDigit(password.charAt(i))){
numberOfDigit++;
}
}
}
if (numberOfDigit < 1) {
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isLowerCase(password.charAt(i))) {
if(isLowerCase(password.charAt(i))){
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1) {
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isUpperCase(password.charAt(i))) {
if(isUpperCase(password.charAt(i))){
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1) {
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch))){
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1) {
checkPassword = false;
}
}
}
return checkPassword;
}
return true;
}
public static boolean isDigit(char ch) {
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch) {
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch) {
return (ch <= 'Z' && ch >= 'A');
}
}
I was able to get your code repeat as long as the 'n' key is not pressed. Right now if any key is pressed other than 'n', it will continue.
One problem was that your while loop needs to be inside of your main. The way it is setup, as soon as the checkPassword returns, there is no way for the program to repeat. Asking for y/n had no way to recall the function. You also had an issue with your string comparison, as #PM 77-1 mentioned in the comments. I would recommend keeping the curly brackets spaced out so it is easier to read, you had a pair of brackets that served no purpose.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
String again;
String n = "n";
while(true)
{
//Prompt user to enter input
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("\nValid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
else
{
System.out.println("\nInvalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
if(again.equals(n))
{
break;
}
}
}
//Program new method
public static boolean checkPassword(String password)
{
boolean checkPassword = true;
//Make sure password is at least 7 digits
if (password.length() < 8)
{
checkPassword = false;
}
else
{
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++)
{
if (isDigit(password.charAt(i)))
{
if(isDigit(password.charAt(i)))
{
numberOfDigit++;
}
}
}
if (numberOfDigit < 1)
{
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isLowerCase(password.charAt(i)))
{
if(isLowerCase(password.charAt(i)))
{
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1)
{
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isUpperCase(password.charAt(i)))
{
if(isUpperCase(password.charAt(i)))
{
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1)
{
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++)
{
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch)))
{
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1)
{
checkPassword = false;
}
}
return checkPassword;
}
public static boolean isDigit(char ch)
{
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch)
{
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch)
{
return (ch <= 'Z' && ch >= 'A');
}
}
I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So this program is supposed to be a game where a user enters a phrase and another user tries to guess the phrase. I'm having a problem with buying a vowel, however. No matter what I enter at line 41 (, it just goes past the loop. I made the validAnswer(String answer) method in the hopes that it would be useful in the loop but it doesn't look to be much help. I know there is a small thing I'm missing but I'm too new to Java to recognize it yet. What am I doing wrong?
I apologize for the long amount of code.
import java.util.Scanner;
public class PhraseGame {
public static void main(String[] args) {
// Initialize scanner
Scanner stdIn = new Scanner(System.in);
// Initialize variables
String sPhrase;
String answer = "f";
char cGuess = 0;
char vGuess = 0;
int count = 0;
int vowels = 0;
int consonants = 0;
int spaces = 0;
boolean gameOver = false;
boolean correct = true;
// Start the "fun" game
System.out.print("Please enter the phrase to guess at: ");
sPhrase = stdIn.nextLine();
// Create the temporary Array
char [] tmpArr = new char[sPhrase.length()];
for (int i = 0; i < sPhrase.length(); i++) {
tmpArr[i] = sPhrase.charAt(i);
}
// Gets the number of spaces
spaces = initTemplateArray(sPhrase, tmpArr, spaces);
printTemplateArray(tmpArr);
while (!(endGame(gameOver, spaces, consonants, vowels, sPhrase))) {
cGuess = getConsonant(stdIn, cGuess);
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.next();
if (answer == "y") {
getVowel(stdIn, vGuess); }
else if (answer == "n"){
break;
}
} while (!validAnswer(answer));
// Updates the array and prints it
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, count, vowels, consonants);
printTemplateArray(tmpArr);
// Checks if the game is over
endGame(gameOver, spaces, consonants, vowels, sPhrase);
}
}
// returns the number of space characters used in the common phrase
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces) {
for (int i = 0; i < sPhrase.length(); i++) {
if (tmpArr[i] != ' ') {
tmpArr[i] = '?';
} else {
tmpArr[i] = ' ';
spaces++;
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr) {
System.out.println("\nCommon Phrase");
System.out.println("-------------");
for (int i = 0; i < tmpArr.length; i++) {
System.out.print(tmpArr[i]);
}
}
public static boolean isVowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
public static char getConsonant(Scanner stdIn, char cGuess) {
do {
System.out.println("\nEnter a lowercase consonant guess: ");
cGuess = stdIn.next().charAt(0);
} while (isVowel(cGuess));
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess) {
do {
System.out.println("\nEnter a lowercase vowel guess: ");
vGuess = stdIn.next().charAt(0);
} while (!(isVowel(vGuess)));
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int count, int vowels, int consonants) {
for (int i = 0; i < sPhrase.length(); i++) {
if (cGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
consonants++;
}
if (vGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
vowels++;
}
}
return count & vowels & consonants;
}
public static boolean endGame(boolean gameOver, int spaces, int consonants, int vowels, String sPhrase) {
int total = spaces + consonants + vowels;
if (total == sPhrase.length()) {
return true;
}
else {
return false;
}
}
public static boolean validAnswer(String answer) {
if (answer.equalsIgnoreCase("y")) {
return true;
}
else if (answer.equalsIgnoreCase("n")) {
return true;
}
else {
return false;
}
}
}
You need to check for null.
public static boolean validAnswer(String answer) {
if (answer!=null && (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n"))) {
return true;
}
return false;
}
or an other unconventional way.
public static boolean validAnswer(String answer) {
if ("y".equalsIgnoreCase(answer) || "n".equalsIgnoreCase(answer))) {
return true;
}
return false;
}
You need to fix
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.nextLine();
if ("y".equalsIgnoreCase(answer)) {
getVowel(stdIn, vGuess);
} else if ("n".equalsIgnoreCase(answer)){
break;
}
} while (!validAnswer(answer));
import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}
I'm a beginner taking Intro to Computer Science and I'm working with java. I get the following error in this program when trying to read from multiple txt files in the getLetterGrade method:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
import java.util.Scanner;
import java.io.*;
public class Exam
{
private int grade;
private float examAvg;
private String name;
private File exam1Data;
private File exam2Data;
private File namesData;
private Scanner inFileExam1;
private Scanner inFileExam2;
private Scanner inFileName;
//constructor
public Exam() throws IOException
{
exam1Data = new File("exam1.txt");
exam2Data = new File("exam2.txt");
namesData = new File("names.txt");
inFileExam1 = new Scanner(exam1Data);
inFileExam2 = new Scanner(exam2Data);
inFileName = new Scanner(namesData);
}
public float getExam1Avg()
{
examAvg = 0;
while (inFileExam1.hasNext()) {
grade = inFileExam1.nextInt();
examAvg += grade;
}
inFileExam1.close();
examAvg = (float)(examAvg / 25.0);
return examAvg;
}
public float getExam2Avg()
{
examAvg = 0;
while (inFileExam2.hasNext()) {
grade = inFileExam2.nextInt();
examAvg += grade;
}
inFileExam2.close();
examAvg = (float)(examAvg / 25.0);
return examAvg;
}
//method that finds the letter grade given a student name and
//the exam number
public char getLetterGrade(String inputName, int examNum)
{
char letter;
int count = 1;
//inputName = inputName.toLowerCase();
do {
if (inFileName.hasNext()){
name = inFileName.nextLine();
}
count++;
} while (inFileName.hasNext() && !name.equalsIgnoreCase(inputName));
inFileName.close();
if (!name.equalsIgnoreCase(inputName)) {
return 'x';
}
if (examNum == 1) {
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
}
else if (examNum == 2) {
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
}
else {
return 'x';
}
if (grade >= 90) {
letter = 'A';
}
else if (grade < 90 && grade >= 80) {
letter = 'B';
}
else if (grade < 80 && grade >= 70) {
letter = 'C';
}
else if (grade < 70 && grade >= 60) {
letter = 'D';
}
else {
letter = 'F';
}
return letter;
}
}
The error occurs at the following line:
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
Please help!!
Here is the main class:
import java.util.Scanner;
import java.io.*;
public class ExamAverages
{
public static void main(String[] args) throws IOException
{
Exam exam = new Exam();
System.out.println(exam.getExam1Avg());
System.out.println(exam.getExam2Avg());
System.out.println(exam.getLetterGrade("name", 1));
}
First of all, you're resetting grade every time you read a line, and you aren't doing anything with it, so that part of the code is useless.
But to answer your question:
According to the API, Scanner only returns an IllegalStateException after the object is closed using Scanner.close() or is somehow closed by the system.
Try moving your Scanner declaration for inFileExam1 next to where you are using it, like this:
if (examNum == 1) {
inFileExam1 = new Scanner(exam1Data); // Add this
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
}
else if (examNum == 2) {
inFileExam2 = new Scanner(exam2Data); // And this
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
}
}
Your error is in getAverageExam1Avg and the other one. Instead of closing your Scanners in the getLetterGrade method, you should keep them open and add a close method like this:
public void close() {
inFileName.close();
inFileExam1.close();
inFileExam2.close();
}
Make sure to add the proper exceptions into that code.
The reason it is failing now is because you haven't opened the Scanners. Un-comment the instantiations in the constructor.
If this doesn't work, I have no idea what will.
you are closing your scanner
inFileName.close();
and then trying to use it again without opening as like:
inFileName = new Scanner(..);
EDIT1
It does not fail for me, but maybe i have missed some stuff (I still don't know how exactly you are willing to read these files, how they relate to each other)
public char getLetterGrade(String inputName, int examNum) {
char letter;
int count = 0;
do {
if (inFileName.hasNext()) {
name = inFileName.nextLine();
}
count++;
} while (inFileName.hasNext() && !name.equalsIgnoreCase(inputName));
if (!name.equalsIgnoreCase(inputName)) {
return 'x';
}
if (examNum == 1) {
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
} else if (examNum == 2) {
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
} else {
return 'x';
}
if (grade >= 90) {
letter = 'A';
} else if (grade < 90 && grade >= 80) {
letter = 'B';
} else if (grade < 80 && grade >= 70) {
letter = 'C';
} else if (grade < 70 && grade >= 60) {
letter = 'D';
} else {
letter = 'F';
}
return letter;
}
You don't include the code that has your main method, but I'm going to make an educated guess that you construct a new Exam object in it, and call getLetterGrade more than once. Since you open your Scanners in the constructor, and close them after reading, the second time you call getLetterGrade you will see an IllegalStateException.
If this psychic reading is inaccurate, can you please update your post with the contents of main(String[] args)?
EDIT: After your latest edit I see that you call the getExam1Avg method before calling getLetterGrade. Since getExam1Avg calls close on your Scanner you get an IllegalStateException when calling the other method. You need to either instantiate a new scanner for each method call or otherwise reset the scanners after each method is complete.