import java.util.*;
public class Hangman
{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter word: ");
String Word = kybd.nextLine();
String dashWord = Word.replaceAll(".", "-");
System.out.println(dashWord);
StringBuilder dashWordB = new StringBuilder(dashWord);
System.out.println("Please guess a letter: ");
char letterGuess = kybd.next().charAt(0);
int lettersGuessed = 0;
// While loop should exit once letterGuessed is equal to Word.length()
while (lettersGuessed <= Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == Word.length() - 1)
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
}
}
System.out.println(dashWordB);
System.out.println(lettersGuessed);
}
}
Having trouble exiting while loop when all letters of dashWordB are guessed correctly. Any help greatly appreciated.
Just add the following in your while loop:
if(lettersGuessed == Word.length()){
break;
}
That should help you fix the problem.
Also as suggested by the others change the while condition to the following:
while (lettersGuessed < Word.length())
So your while loop should be the following:
while (lettersGuessed < Word.length()){
for (int i=0; i < Word.length(); i++)
{
if (Word.charAt(i) == letterGuess)
{
dashWordB.setCharAt(i,letterGuess);
lettersGuessed++;
System.out.println("letters guessed: " + lettersGuessed);
System.out.println("word length: " + Word.length());
}
if (i == (Word.length() - 1))
{
i = -1;
System.out.println(dashWordB);
System.out.println("Have another guess: ");
letterGuess = kybd.next().charAt(0);
}
if(lettersGuessed == Word.length()){
break;
}
}
}
Your problem is here: while (lettersGuessed <= Word.length()){
You will exit only if lettersGuessed > Word.length() or if you guessed correctly a letter more than the length of the word.
Try while (lettersGuessed < Word.length()){
Related
I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}
package Demo;
import java.util.Scanner;
public class seat_reservation{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// Initialization
final int ROWS = 2;
final int COLS = 3;
char [][] seats = new char [ROWS][COLS];
int i, j, seatNum, counter = 0;
char seatLetter = 'A';
int choice = 0;
String seatEnter;
boolean cont = true; // loops of running the program
while( choice != 4 ){
System.out.print( "1. Assign Seats" );
System.out.print( "2. Exit" );
System.out.print( "Select your choice: " );
choice = read.nextInt();
switch( choice ){
case 1:
//Set the value.
for (i=0; i < seats.length; i++) {
for (j=0; j < seats[i].length; j++)
seats[i][j] = seatLetter++;
seatLetter = 'A'; // to reset the value to A for the new loop
}
//To display the list of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j]+" ");
System.out.println();
}
//condition
while (counter < 6 && cont) {
do {
System.out.print("Please type the chosen seat(starts with row and column,e.g:2A):" + "");
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0)+"");
if (seatNum != 0)
seatLetter = seatEnter.charAt(1);
i++;
//if user enters wrong input, error message will appear.
if (seatLetter!='A'){
if (seatLetter!='B'){
if(seatLetter!='C'){
if(seatLetter!='D')
System.out.println ("Invalid! Please enter the correct seat:");
}
}
}
}
//continue to loop until the condition true
while (seatNum < 0 || seatNum > 7 || seatLetter < 'A' || seatLetter > 'D');
if (seatNum == 0) {
cont = false;
} else {
if (seats[seatNum-1][seatLetter-65] == 'X')
System.out.println("Seat have been taken.Please choose another seat:");
else {
seats[seatNum -1][seatLetter-65] = 'X';
counter++;
}
// To display updated lists of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j] + " ");
System.out.println();
}
System.out.println(" ") ;
//}
//}
// displays fully booked message
if (counter == 6)
System.out.println("All seats are now fully-booked.");
break;
}
}
case 2://syntax error here
if (counter == 6)
System.out.println( "All seats are now fully-booked." );
System.out.println( "End of Program" );
System.exit(0);
break;
default:
System.out.println("Error input");
break;//syntax error here as well.
}
}
}
}
The problem is caused due to:
choice = read.nextInt();
The scanner.nextInt() only takes the next token from the input. Rest are ignored by it.
So when you're trying to take the next input from this line and process it, the error occurs:
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0) + "");
As the previous read.nextInt() left the rest except first token, when you hit enter after giving 1 as input, it took only the 1 and the enter or newline token was captured by the read.nextLine(). That is why it got no charAt(0) and thus thrown StringIndexOutOfBoundException.
Try:
choice = Integer.parseInt(read.nextLine());
or,
choice = read.nextInt();
read.nextLine(); // this will capture the residue
I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;
class Battleship {
public static char randChar(){
final String alphabet = "ABCDE";
final int N = alphabet.length();
char rand;
Random r = new Random();
rand = alphabet.charAt(r.nextInt(N));
return rand;
}
public static void main (String[] args) throws java.lang.Exception {
char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
int[] numbers ={1, 2, 3, 4, 5};
int[][] ships = new int[7][2];
char colGuess;
int rowGuess;
Boolean boardFlag=false;
Scanner scan = new Scanner(System.in);
//creates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
System.out.print(letters[j] + "" + numbers[i-1]);
}
System.out.print(" ");
}
System.out.println();
}
//assigns ships to random spots
assignShips(ships);
System.out.println("Enter your guess for the column:");
colGuess = scan.next().charAt(0);
//converts to uppercase
colGuess = Character.toUpperCase(colGuess);
System.out.println("Enter your guess for the row:");
rowGuess = scan.nextInt();
//shows player what they entered
System.out.println("you entered: " + (char) colGuess + rowGuess);
//calls method to check for a hit
fire(colGuess, rowGuess, ships);
boardFlag = fire(colGuess, rowGuess, ships);
System.out.println(boardFlag);
//updates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
if(boardFlag==true) {
System.out.print(" " + "X");
}
}
else {
System.out.print(letters[j] + "" + numbers[i - 1]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void assignShips(int[][] ships) {
Random random = new Random();
for(int ship = 0; ship < 7; ship++) {
ships[ship][0] = randChar();
ships[ship][1] = random.nextInt(5);
//gives location of ships, for testing purposes
System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
}
}
//checks user input to see if we have a hit
public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
Boolean hitFlag=false;
for(int ship = 0; ship < ships.length; ship++){
if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
hitFlag=true;
}
}
if(hitFlag == true) {
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
}
else {
System.out.println("sorry chief we missed em");
}
return hitFlag;
}
}
The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
if(boardFlag==true) {
System.out.print(" "+"X");
}
}
Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.
The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
for (int j = 0 ; j <= 5 ; j++){
if (i == 0) {
System.out.print(letters[j]+" ");
} else if (j == 0){
System.out.print(numbers[i-1] );
} else {
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
}
System.out.print(" ");
}
System.out.println();
}
This block (old version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em");
}
Should be (new version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
}
this will print:
sorry chief we missed em at D3 //D3 is a random possible set of coordinates
Rather than:
sorry chief we missed em //Old version
So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.
Comment if you have any questions!
I have a small hang man type game in which the user guesses a letter and tries to determine one of the random words from a string array. The issue is that once the user wants to play again with a new random word, the old word still shows up along side with it ?
import java.util.Random;
import java.util.Scanner;
import java.lang.Character;
public class Game
{
public static void main(String[] args)
{
String[] words = {"Computer", "Software" , "Program" ,
"Algorithms", "Unix" , "Mathematics" ,
"Quick" , "Bubble" , "Graph" };
Random rnd = new Random();
Scanner sc = new Scanner(System.in);
int index;
String word = "",
invisibleWord = "",
newString = "",
guess,
status;
while(true)
{
index = rnd.nextInt(words.length);
word = words[index];
for(int i = 0; i < word.length(); ++i)
invisibleWord += "*";
while(true){
System.out.print("(Guess) Enter a letter in word "
+ invisibleWord + " > ");
guess = sc.nextLine();
for(int j = 0; j < word.length(); ++j)
if(guess.toUpperCase().equals(Character.toString(word.charAt(j)).toUpperCase())){
if(j == 0){
newString = invisibleWord.substring(0,j) + guess.toUpperCase() + invisibleWord.substring(j + 1);
invisibleWord = newString;
} else {
newString = invisibleWord.substring(0,j) + guess + invisibleWord.substring(j + 1);
invisibleWord = newString;
}
}
if(invisibleWord.contains("*")) continue;
else break;
}
System.out.println("The word is " + word);
System.out.print("Do you want to guess another word ? " +
"Enter y or n > ");
status = sc.nextLine();
if(status.toUpperCase().equals("Y")) continue;
else if(status.toUpperCase().equals("N")) break;
}
}
}
SAMPLE RUN:
(Guess) Enter a letter in word ****** > a
(Guess) Enter a letter in word ****** > e
(Guess) Enter a letter in word *****e > i
(Guess) Enter a letter in word *****e > o
(Guess) Enter a letter in word *****e > u
(Guess) Enter a letter in word *u***e > b
(Guess) Enter a letter in word Bubb*e > l
The word is Bubble
Do you want to guess another word ? Enter y or n > y
(Guess) Enter a letter in word Bubble******** >
The problem occurs in the last line, why is Bubble still showing up as a word when it is supposed to be reset to a new random word ?
your question itself answers it! you need to reset the variable. try following
if(status.toUpperCase().equals("Y"))
{
invisibleWord = "";
continue;
}
You are not resetting invisibleWord after each iteration.
while(true)
{
invisibleWord="";
index = rnd.nextInt(words.length);
word = words[index];
for(int i = 0; i < word.length(); ++i)
invisibleWord += "*";
while(true){
System.out.print("(Guess) Enter a letter in word "
+ invisibleWord + " > ");
guess = sc.nextLine();
for(int j = 0; j < word.length(); ++j)
if(guess.toUpperCase().equals(Character.toString(word.charAt(j)).toUpperCase())){
if(j == 0){
newString = invisibleWord.substring(0,j) + guess.toUpperCase() + invisibleWord.substring(j + 1);
invisibleWord = newString;
} else {
newString = invisibleWord.substring(0,j) + guess + invisibleWord.substring(j + 1);
invisibleWord = newString;
}
}
if(invisibleWord.contains("*")) continue;
else break;
}
System.out.println("The word is " + word);
System.out.print("Do you want to guess another word ? " +
"Enter y or n > ");
status = sc.nextLine();
if(status.toUpperCase().equals("Y")) continue;
else if(status.toUpperCase().equals("N")) break;
}
}
}
I have a program for a hangman game and the indexof is not working for me? its on line 30. I have been trying to figure it out but I cannot.if (guessedWord.indexOf(letter) >= 0). I will keep trying to find out what I did wrong
import java.io.PrintStream;
import java.util.Scanner;
public class Hangman
{
public static void main(String[] args)
{
String[] words = { "write", "program", "that", "receive", "positive" };
Scanner input = new Scanner(System.in);
char anotherGame;
do
{
int index = (int)(Math.random() * words.length);
String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;
while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);
if (guessedWord.indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}
System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses + (numberOfMisses <= 1 ? " time" : " times"));
System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}
You are passing in a char where String is expected. Try using String.valueOf(letter) like this:
if (guessedWord.indexOf(String.valueOf(letter)) >= 0) {
// Your code
}
StringBuilder#indexOf(char) is undefined. You could do
if (guessedWord.indexOf(Character.toString(letter)) >= 0) {
there's no indexOf(char) method for a StringBuilder.
guessedWord.indexOf(letter)
should be
if (guessedWord.toString().indexOf(letter) >= 0) {