Guess A word (Java) - java

Hello I have to create a program that lets the player guess a word. The code I have works fine but I have to write a condition that allows the player 7 tries, if the player does not guess the word on the 7th try he/she losses. I don't know how to write this condition. Here is my code:
package javaapplication5;
import java.io.*;
import java.lang.*;
import java.util.*;
public class NewClass2{
public static int ReadWordsFromFile(String[] words)
{
try
{
FileReader fr = new FileReader("Guess_words.txt");
BufferedReader br = new BufferedReader(fr);
int count = 0;
for (int i = 0; i <87; i++)
{
String s = br.readLine();
if (s == null)
break;
words[count++] = s;
}
fr.close();
return count;
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
return -1;
}
catch (IOException err)
{
System.out.println(err.getStackTrace());
return -1;
}
}
static public String ReadString()
{
try
{
String inpString = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return reader.readLine();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
public static void main(String[] args)
{
System.out.println("Welcome to Guess a Word\n");
String[] words = new String[87];
int count = ReadWordsFromFile(words);
if (count < 0)
{
System.out.println("No words found in the file");
return;
}
if (words == null)
return; // Exception message was already shown
int x = (int)(Math.random() * 87);
int guessX = (x % count);
String secretWord = words[guessX];
int numChars = secretWord.length();
System.out.print("Your secret word is: ");
for(int i = 0; i < numChars; i++)
System.out.print("*");
System.out.println();
boolean bGuessedCorrectly = false;
System.out.println("Guess now (To stop the program, enter #) : ");
while (true)
{
String choice = ReadString();
if (choice.startsWith("#"))
break;
if (choice.compareTo(secretWord) == 0)
{
bGuessedCorrectly = true;
break;
}
for (int i = 0; i < numChars; i++)
{
if (i < secretWord.length() &&
i < choice.length())
{
if (secretWord.charAt(i) == choice.charAt(i))
System.out.print(choice.charAt(i));
else
System.out.print("*");
}
else
System.out.print("*");
}
System.out.println();
}
if (bGuessedCorrectly == false)
System.out.println("Unfortunately you did not guess it correctly. The secret word is: " + secretWord);
else
System.out.println("Congrats! You have guessed it correctly");
}
}

Why not simply change your loop from this:
while (true) {
}
To this:
for (int nrOfGuesses = 0; nrOfGuesses < 7; nrOfGuesses++) {
// do stuff
}

Related

Java NumberFormatException in list reading application

I wrote code for a program that reads a file containing a list of numbers and outputs, for each number in the list, the next bigger number. I'm using eclipse for this project and when i go an run the program I'm getting an error and i cant seem how to fix it.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string:
"78,22,56,99,12,14,17,15,1,144,37,23,47,88,3,19"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at numbers.main(numbers.java:25)
Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class numbers {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> nextList = new ArrayList<Integer>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// read the list of number from file
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
// loop through each number
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int max = Integer.MAX_VALUE;
// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
// print the numbers
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + " : " + nextList.get(i));
}
} catch (FileNotFoundException e) {
// if file not found
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the file at the end
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
You need to split ( and also trim() ) your line over a comma (,) and then parse over all the elements you obtain.
Hope this solves your query.
The issue is you are trying to convert a string with multiple numbers to a single integer, which is causing your exception. Try this instead:
while ((text = reader.readLine()) != null) {
String [] textArray = text.split(",");
for (int i = 0; i < textArray.length; i++) {
list.add(Integer.parseInt(textArray[i]));
}
}
String line="";
while ((text = reader.readLine()) != null) {
line=text; //read the text
}
line.trim();
// loop through each number
for(String num:line.split(",")){
list.add(Integer.parseInt(num)); //add the item to the list
}
The text could have some non numeric characters so you should check about them so try like this
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
List<Integer> nextList = new ArrayList<>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text;
while ((text = reader.readLine()) != null) {// read the list of number from file
if(!text.isEmpty()) {
try {
if (text.contains(",")) {
for (String str : text.split(",")) {
list.add(Integer.parseInt(str));
}
}
else if(text.matches("[+-]?[0-9]+")) {
list.add(Integer.parseInt(text));
}
else {
System.out.println("this is not a number : " + text);
}
} catch (NumberFormatException e){
System.out.println("this is not a number : "+ text);
}
}
}
for (int i = 0; i < list.size(); i++) {// loop through each number
int num = list.get(i);
int max = Integer.MAX_VALUE;// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
for (int i = 0; i < list.size(); i++) {// print the numbers
System.out.println(list.get(i) + " : " + nextList.get(i));
}
}
catch (FileNotFoundException e) {// if file not found
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {// close the file at the end
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
}
}
}

JAVA trying to read a file it sets nextChar equal to a box thing instead of the next char in the save file. where have I gone wrong?

this is a debugger error and runs an infinite loop where shown.
I am trying to load a file and have the gameboard be set to the chars in the text file (which are saved previously by user as shown) but in the debugger problem it sets next nextChar infinitely to □ after the first char has been read. I have had multiple attempts at trying to fix this myself but I cannot find a solution. Any help on how to fix this bug would be greatly appreciated. If any more details are needed give voice and see questions answered hastily.
This is the saving section of code.
/**
* A method to save the current state of the game
*/
public static void saveGame()
{
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try
{
System.out.println("Please name the save game file.");
outputStream = new FileOutputStream(Genio.getString());
printWriter = new PrintWriter(outputStream);
int i, j =0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printWriter.println(gameBoard[i][j]);
}
}
}
catch (IOException e)
{
System.out.println("Sorry an error occured during saving.");
}
finally
{
if (printWriter != null)
{
printWriter.close();
}
}
}
This is the loading section of code;
/**
* A method to load a game.
*/
public static void loadGame()
{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
char nextChar;
String line;
try
{
System.out.println("Please enter the name of your save file:");
fileReader = new FileReader(Genio.getString());
bufferedReader = new BufferedReader(fileReader);
nextChar = (char)bufferedReader.read();
while ((line = bufferedReader.readLine()) != null)
{
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
if (nextChar == '-' || nextChar == 'Y' || nextChar == 'R') //Infinite loop here where nextChar = □
{
gameBoard[i][j] = nextChar;
nextChar = (char)bufferedReader.read();
System.out.print(gameBoard[i][j]);
line = bufferedReader.readLine();
}
else
{
nextChar = (char)bufferedReader.read();
j--;
}
}
System.out.print("\n");
}
line = bufferedReader.readLine();
}
System.out.println("1\t2\t3\t4\t5\t6\t7");
}
catch (IOException e)
{
System.out.println("Sorry an error occured during the loading of the file.");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
System.out.println("Sorry, an error has occured when closing the file.");
}
}
}
}
Not sure why you are reading a line AND reading characters.
You need to read each line and process each character in that line, for example...
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadConnect4 {
private static final String TEST_BOARD = "-------\n"
+ "-------\n"
+ "-------\n"
+ "-------\n"
+ "-Y-----\n"
+ "-Y--R--\n";
private static final int ROWS = 6;
private static final int COLS = 7;
public static void main(String[] args) throws Exception {
ByteArrayInputStream pretendFile = new ByteArrayInputStream(TEST_BOARD.getBytes());
char[][] board = readBoard(pretendFile);
printBoard(board);
}
private static void printBoard(char[][] board) {
for(int k = 0; k < board.length; k++) {
for(int j = 0; j < board[k].length; j++) {
System.out.print(board[k][j]);
}
System.out.println();
}
}
private static char[][] readBoard(InputStream stream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
int row = 0;
char[][] result = new char[ROWS][COLS];
// Read each line, stop when end of file (line is null)...
while((line = reader.readLine()) != null) {
// For each column...
for(int col = 0; col < 7; col++) {
// Get character from line, store in array
result[row][col] = line.charAt(col);
}
row++;
}
return result;
}
}
OUTPUT:
-------
-------
-------
-------
-Y-----
-Y--R--
To answer your question "why does it read box things", it's probably reading the end-of-stream and returning the character equivalent of "-1"

Counting { and } braces in program JAVA

I have to read an input file that contains codes and produce an output that matches the corresponding braces ({ and })
example of how output will look
import java.util.scanner;
public class Tester {1
public static void main(String[] args) {2
Scanner in = new Scanner (System.in);
int price = in.nextInt;
if (price < 10)
System.out.println("Good price");
System.out.println ("Buy it");
}2
}1
}0
}0
0 will represent extra braces that has no matches.
What is the most efficient way to approach this?
Should I just process line by line with Strings?
You can keep a count. Iterate the characters in every line, increment (or decrement) the count and (output the count) for { and } respectively. Don't forget to close your Scanner with a finally block or a try-with-resources. Assuming your file Tester.java is in the user's home folder you could do something like,
File f = new File(System.getProperty("user.home"), "Tester.java");
try (Scanner scan = new Scanner(f)) {
int count = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (char ch : line.toCharArray()) {
System.out.print(ch);
if (ch == '{') {
System.out.print(++count);
} else if (ch == '}') {
if (count > 0) {
System.out.print(--count);
} else {
System.out.print(count);
}
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
You can find the extra braces by making use of stack as below:
public static void main(final String[] args) {
Stack<String> stack = new Stack<String>();
File file = new File("InputFile");
int lineCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
lineCount++;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '{') {
stack.push("{");
} else if (line.charAt(i) == '}') {
if (!stack.isEmpty()) {
stack.pop();
} else {
System.out.println("Extra brace found at line number : " + lineCount);
}
}
}
}
if (!stack.isEmpty()) {
System.out.println(stack.size() + " braces are opend but not closed ");
}
} catch (Exception e) {
e.printStackTrace();
}
}

When reading file with Java Scanner, it hangs after the last line has been processed

My method is able to read all the lines of the file but then it gets stuck at the last line and never reaches scanner.close() and onwards. I'm not sure why? I invoke scanner.nextLine() so surely it should detect this and scanner.hasNextLine() should return false when the file ends. Is there a quick fix that I have overlooked here?
private int[] GetNumberOfRowsAndColumns(BufferedReader br) {
Scanner scanner = new Scanner(br);
String line = "";
int column_max = 0;
int total_rows = 0;
int[] result = new int[1];
try {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.length() > column_max) {
column_max = line.length();
}
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
}
scanner.close();
result[0] = column_max;
result[1] = total_rows;
return result;
}
The file in question:
+++++++++++++++++
+0A +
+AA ++++
+ +
+ ++A+
+ +a+
+++++++++++++++++
EDIT:
public SearchClient(BufferedReader serverMessages) throws Exception {
Map<Character, String> colors = new HashMap<Character, String>();
String line, color;
int agentCol = -1, agentRow = -1;
int colorLines = 0, levelLines = 0;
// Read lines specifying colors
while ((line = serverMessages.readLine())
.matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) {
line = line.replaceAll("\\s", "");
String[] colonSplit = line.split(":");
color = colonSplit[0].trim();
for (String id : colonSplit[1].split(",")) {
colors.put(id.trim().charAt(0), color);
}
colorLines++;
}
if (colorLines > 0) {
error("Box colors not supported");
}
int[] result = getNumberOfRowsAndColumns(serverMessages);
System.err.println("MAX COLUMNS = " + result[0]);
System.err.println("MAX ROWS = " + result[1]);
initialState = new Node(null);
while (!line.equals("")) {
for (int i = 0; i < line.length(); i++) {
char chr = line.charAt(i);
if ('+' == chr) { // Walls
initialState.walls[levelLines][i] = true;
} else if ('0' <= chr && chr <= '9') { // Agents
if (agentCol != -1 || agentRow != -1) {
error("Not a single agent level");
}
initialState.agentRow = levelLines;
initialState.agentCol = i;
} else if ('A' <= chr && chr <= 'Z') { // Boxes
initialState.boxes[levelLines][i] = chr;
} else if ('a' <= chr && chr <= 'z') { // Goal cells
initialState.goals[levelLines][i] = chr;
}
}
line = serverMessages.readLine();
levelLines++;
}
}
By convention, Java methods start with a lower case letter. Next, your array can only hold one value (length of 1) and you don't need a Scanner (use your BufferedReader). Finally, you can make an anonymous array. Something like,
private int[] getNumberOfRowsAndColumns(BufferedReader br) {
int column_max = 0;
int total_rows = 0;
try {
String line;
while ((line = br.readLine()) != null) {
// if (line.length() > column_max) {
// column_max = line.length();
// }
column_max = Math.max(column_max, line.length());
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new int[] { column_max, total_rows };
}

Runtime error on ACM-ICPC Live Archive 3242 - Da Vinci's Cryptex

I've submitted many solutions written in Java for this problem on ACM-ICPC Live archive. I followed, strictly all the instructions of writing Java solutions. I even installed JDK 6 on my IDE but I always get Runtime error, any idea what is throwing exception here 'cos I think I handled all exceptions.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
class Main {
BufferedReader read;
BufferedWriter write;
Integer D, N;
String U, S;
ArrayList<String> cryptex;
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
read = new BufferedReader(new InputStreamReader(System.in));
write = new BufferedWriter(new OutputStreamWriter(System.out));
process();
try {
read.close();
write.flush();
write.close();
} catch (IOException ex) {
return;
}
}
private void process() {
try {
D = Integer.parseInt(read.readLine().trim());
} catch (IOException ex) {
return;
}
for (int i = 0; i < D; i++) {
try {
String[] params = read.readLine().trim().split("\\s+");
if (params.length != 3) {
return;
}
N = Integer.parseInt(params[0]);
U = params[1];
S = params[2];
cryptex = new ArrayList<String>(N);
for (int j = 0; j < N; j++) {
cryptex.add(read.readLine().trim());
}
try {
write.write(U + " " + solveCase());
} catch (Exception ex) {
return;
}
write.newLine();
read.readLine();
} catch (IOException ex) {
return;
}
}
}
private String solveCase() throws Exception {
Integer n = null, f = null, add = null;
for (int i = 0; i < N; i++) {
if (S.charAt(i) != '_') {
n = cryptex.get(i).indexOf(S.charAt(i));
f = cryptex.get(i).indexOf(U.charAt(i));
add = n - f;
break;
}
}
if (n == null || f == null || add == null) {
throw new Exception("Incorrect test case exception.");
}
char[] ret = S.toCharArray();
for (int i = 0; i < N; i++) {
f = cryptex.get(i).indexOf(U.charAt(i));
n = (add + f + 26) % 26;
ret[i] = cryptex.get(i).charAt(n);
}
return new String(ret);
}
}
Any idea on what I might be doing wrong?
In your process method, you call
D = Integer.parseInt(read.readLine().trim());
This is not optimal. Use a scanner.
Your line should look more like this:
Scanner sc = new Scanner(System.in);
//...
try {
D = sc.nextInt(); // Number of test cases
N = sc.nextInt(); // Rings
U = sc.next(); // Unlocking word
}
//...
Also, note that there will likely be more than one test case, so process() or some other method will need to be inside a for loop.

Categories