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.
Related
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.
The issue I'm having is that the 2D array is not printing out everything in the array, and when I run the evolve method, it doesn't print out the 2D array the same as the first time. Wondering what's wrong to make it not print out the entire array, and not print the array the same way when the evolve method runs? Each print out of the array needs to be in a 25x75 grid
Desired initial result:
Actual result:
evolve method result:
Project 4:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in); // Created a scanner
System.out.println("Enter the file name you would like to use");
File file = new File(input.nextLine()); // Takes file name to find file
Scanner inputFromFile = new Scanner(file);
FileInputStream fileInput = new FileInputStream(file); // reads file
int r;
int y = 0;
int i = 0;
while ((r = fileInput.read()) != -1) { // goes through each character in
// file, char by char
char c = (char) r;
GameOfLife.grid[i][y] = c;
y++;
if (y == 75) {
y = 0;
i++;
if (i == 25) {
break;
}
}
}
// Prints the initial environment
System.out.println("Initial set: ");
for (int j = 0; j < GameOfLife.grid.length; j++) {
System.out.print(GameOfLife.grid[j]);
}
boolean operate = true;
while (operate = true) {
System.out.println("Do you want to see the next generation? Y/N?");
String q = input.nextLine();
if (q.equalsIgnoreCase("y")) {
GameOfLife.evolve();
for (int j = 0; j < GameOfLife.grid.length; j++) {
System.out.print(GameOfLife.grid[j]);
operate = true;
}
} else {
operate = false;
System.exit(0);
}
}
}
}
GameOfLife:
import java.util.Arrays;
public class GameOfLife {
static final int m = 25; // number of rows
static final int n = 75; // number of columns
static char[][] grid = new char[m][n]; // Creates an empty (no dots or
// X's)grid of rows and columns.
static int count_neighbors(int i, int j) {
int nn = 0; // number of neighbors of cell(i,j)
if (i > 0 && j > 0 && grid[i - 1][j - 1] == 'X') {
nn++;
}
;
if (i > 0 && grid[i - 1][j] == 'X') {
nn++;
}
;
if (i > 0 && j < 72 && grid[i - 1][j + 1] == 'X') {
nn++;
}
;
if (j > 0 && grid[i][j - 1] == 'X') {
nn++;
}
;
if (j < 72 && grid[i][j + 1] == 'X') {
nn++;
}
;
if (j > 0 && i < 22 && grid[i + 1][j - 1] == 'X') {
nn++;
}
;
if (i < 22 && grid[i + 1][j] == 'X') {
nn++;
}
;
if (i < 22 && j < 72 && grid[i + 1][j + 1] == 'X') {
nn++;
}
return nn;
}
static void evolve() {
for (int i = 0; i < 23; i++) {
for (int j = 0; j < 73; j++) {
int s = count_neighbors(i, j);
if (s < 2) {
grid[i][j] = '.';
}
if (s == 2 || s == 3) {
grid[i][j] = 'X';
}
if (s > 3) {
grid[i][j] = '.';
}
}
}
}
}
Add a System.out.println() after each for-loop to start printing the grid on the next line.
// Print out grid.length characters
for (int j = 0; j < GameOfLife.grid.length; j++) {
System.out.print(GameOfLife.grid[j]);
}
// Print a new line
System.out.println();
Updated
The problem I failed to notice above is that you are printing an entire row in one line, and the whole grid in one (visible) loop. The following System.out.println() would therefore print a blank line after the entire grid is printed. Please see my solution which extracts out the printing of the game, uses a try-catch for the file reader, and removes the unnecessary operate variable at the bottom since you were just exiting anyway.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Project4 {
private static void printGame() {
for (char[] row : GameOfLife.grid) {
for (char c : row) {
System.out.print(c);
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in); // Created a scanner
System.out.println("Enter the file name you would like to use");
File file = new File(input.nextLine()); // Takes file name to find file
BufferedReader br = null;
String line;
int i = 0;
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
for (int col = 0; col < line.length(); col++) {
GameOfLife.grid[i][col] = line.charAt(col);
}
i++;
if (i == 25) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
}
// Prints the initial environment
System.out.println("Initial set: ");
printGame();
while (true) {
System.out.println("Do you want to see the next generation? Y/N?");
String q = input.nextLine();
if (q.equalsIgnoreCase("y")) {
GameOfLife.evolve();
printGame();
} else {
System.exit(0);
}
}
}
}
I think you should try using println this in both places like this:
System.out.println(GameOfLife.grid[j]);
System.out.print() is not flushed automatically, it's only flushed when a newline is written. This means that rather than writing out everything, it might buffer the IO to keep things more efficient.
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 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?
so in my program im trying to incorporate a couple of different classse into my main program which i am coming up with the code.
What i am given
Dictionary() {
dictionary = new String[NUMBER_OF_WORDS];
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(FILE_NAME));
}catch (FileNotFoundException e) {
System.out.println("Dictionary class cannot find file \"dictionaryData.txt\".");
System.out.println("Please make sure that the file is in the project folder.");
System.exit(0);
}
for (int i = 0; i < NUMBER_OF_WORDS; i++) {
dictionary[i] = inputStream.next();
}
}
public String getRandomWord(){
Random generator = new Random();
String temp = new String();
temp += dictionary[generator.nextInt(NUMBER_OF_WORDS)];
return temp;
}
public boolean find(String word) {
int count = 0;
int lowerIndex = 0;
int upperIndex = NUMBER_OF_WORDS - 1;
int middleIndex;
while(lowerIndex <= upperIndex){
middleIndex = (lowerIndex + upperIndex) / 2;
count++;
if(word.equalsIgnoreCase(dictionary[middleIndex])) { // found it
return true;
}
else if (word.compareToIgnoreCase(dictionary[middleIndex]) < 0) { // word smaller than middle
upperIndex = middleIndex - 1;
}
else { // word is larger than middle
lowerIndex = middleIndex + 1;
}
}
return false;
}
}
along with another class WordHider
WordHider() {
secretWord = new String();
wordMask = new String();
}
public String getWordMask() {
return wordMask;
}
public String getSecretWord() {
return secretWord;
}
public void setSecretWord(String newSecretWord) {
secretWord = newSecretWord.toLowerCase();
if (secretWord.length() > 0) {
wordMask = HIDE_CHAR;
for (int i = 1; i < secretWord.length(); i++) {
wordMask += HIDE_CHAR;
}
}
}
public boolean isHiddenWordFound() {
for (int i = 0; i < wordMask.length(); i++) {
if(wordMask.charAt(i) == HIDE_CHAR.charAt(0)) {
return false;
}
}
return true;
}
public int revealLetter(String letter) {
int count = 0;
String newFoundWord = "";
if (letter.length() == 1) {
for (int i = 0; i < secretWord.length(); i++) {
if ((secretWord.charAt(i) == letter.charAt(0))
&& (wordMask.charAt(i) == HIDE_CHAR.charAt(0))) {
count++;
newFoundWord += letter;
}
else {
newFoundWord += wordMask.charAt(i);
}
}
}
wordMask = newFoundWord;
return count;
}
}
and using those classes i have to come up with code that looks like this:
Word: ********** Guesses Left: 5
Enter your guess: a
Miss!
Word: ********** Guesses Left: 4
Enter your guess: e
Miss!
Word: ********** Guesses Left: 3
Enter your guess: i
Word: i**i*i**** Guesses Left: 3
Enter your guess: o
Word: i**i*i*o** Guesses Left: 3
And ive got a couple of questions about this,
1) i have a dictionaryData.text that i was given and have to implement
that into my code. it contains a list of 81thousand words and im not
sure how to have my program recognize its there. Dictionary class
cannot find file "dictionaryData.txt". Please make sure that the file
is in the project folder. ^ i get that error when i try and print a
random word
2) How do i get my program to change the letters of a word to
stars(Hide the word)
3) put it all in a loop?
Parts of the Dictionary class and the WordHider class are missing. Nevertheless, I'll try and answer your questions.
1) Like I said, you're missing part of the Dictionary class. You incorporate the class like this:
Dictionary dictionary = new Dictionary();
String word = dictionary.getRandomWord();
2) Like this:
wordHider.setSecretWord(word);
3) I'm not sure what "it" is, but yes, your user has to guess a letter. Then you have to check to see if the letter is in the word. Like this:
wordHider.revealLetter(letter);
Then you have to display the word and let the user guess another letter. This guess / check / display has to be in a loop.