trouble with char in java - java

I am practicing and I want to create a code with a infinite loop the while loop, but my problem is that I don't know how to compare char or read char from the keyboard. So, far I have done the code below, any suggestions please ?
Scanner keyboard = new Scanner(System.in);
System.out.println("Guess my favorite character: ");
String letter = keyboard.nextLine();
char secret = 'a';
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.chartAt(i).equals('a')) {
break;
}
}
System.out.println("YOU got it!");
}
}
}

break only jumps out of the for loop, so you have a infinite while true loop. You may want to try this way.
Scanner keyboard = new Scanner(System.in);
System.out.println("Guess my favorite character: ");
String letter = keyboard.nextLine();
char secret = 'a';
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.chartAt(i).equals('a')) {
System.out.println("YOU got it!");
return;
}
}
}

Try like this;
String secret = "a";
Boolean isFounded = false;
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.equals(secret)) {
System.out.println("YOU got it!");
isFounded = true;
}
if(isFounded) break;
}
if(isFounded) break;
}

Only one loop here give it a try.
String secret = "a";
String guess = "";
Scanner keyboard = new Scanner(System.in);
while(!guess.contains(secret)){
System.out.println(" Enter guess:");
guess = keyboard.nextLine();
}
System.out.println("YOU got it!");

Related

How to go back to the beginning of a code without ending it?

I want to go back to the beginning of my code in order to print multiple things and allow people to add multiple “drawings” to a picture without ending the code
Here’s my code:
package com.company;
import java.util.Scanner;
public class Art {
public static void main(String[] args) {
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
String response1 = scan1.nextLine();
}
}
Use a do-while loop to go inside the loop at least once.
You are asking at the end if he wants to add more, you should give the User a choice like type in 'Y' for more.
The 'Y' is here just a dummy value you can replace it with anything you want this should just be an example.
Then you compare the typed in value in the condition of your while()
When the value you are asking for was typed in then go ahead and loop through it again.
import java.util.*;
public class MyClass {
public static void main(String[] args){
String response1;
do{
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
response1 = scan1.nextLine();
}while(response1.equals("Y"));
}
}
Surround your code with while(true)
while (true)
{
// add your code here
}
You can break the loop by using 'break;'

How to break from a loop after finding a word

I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.

Scanner results works fine in a IF using int but not String (phonebook) [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm currently on a project where I'm supposed to create a phonebook in java with eclipse, I'm almost done but there's still one part of my code that I don't understand.
The following code sample is the part giving me some troubles, my condition if(...contains(...)) always answers true even if none of the contact have this part of String in their name. Also the whole contacts of the phone are displayed while I would like only the one that match.
I've tried to do with if(...contains(..) == true) but it's not working either.
On the other hand the second part looking for a matching with ID works perfectly and give back only the concerned "i". Using the same code but adapted to my String also doesn't produce any good result.
public static void display(){
System.out.println("You selected display a contact, choose an option :");
System.out.println("1. by the first name");
System.out.println("2. by the last name");
System.out.println("3. by the ID");
System.out.println("4. by the phone number");
Scanner sc = new Scanner(System.in);
int str3 = sc.nextInt();
if(str3 == 1){
System.out.println("Please enter the first name of the contact");
String fname = sc.nextLine();
sc.nextLine();
for(int i = 0; i <= (phoneBook.size()-1) ; i++){
if(((phoneBook.get(i)).getFirstName()).toLowerCase().contains(fname.toLowerCase()) ){
displayContact(phoneBook.get(i));
}
}}
if(str3 == 2){
System.out.println("Please enter the last name of the contact");
String lname = sc.nextLine();
sc.nextLine();
for(int i = 0; i <= (phoneBook.size()-1) ; i++){
if(((phoneBook.get(i)).getLastName()).toLowerCase().contains(lname.toLowerCase())){
displayContact(phoneBook.get(i));
}
}
}
if(str3 == 3){
System.out.println("Please enter the ID of the contact");
int id = sc.nextInt();
for(int i = 0; i <= (phoneBook.size()-1) ; i++){
if(id == ((phoneBook.get(i)).getID())){
displayContact(phoneBook.get(i));
}
}
}
if(str3 == 4){
System.out.println("Please enter the phone number of the contact");
int phnb = sc.nextInt();
for(int i = 0; i <= (phoneBook.size()-1) ; i++){
if(phnb == phoneBook.get(i).getPhoneNb()){
displayContact(phoneBook.get(i));
}
}
}
System.out.println(" ");
System.out.println("If you want to go back at main menu press 1, else press 2 to quit.");
int str8 = sc.nextInt();
if(str8 == 1){
menu();
}
if(str8 == 2){
quit();
}
}
I think the usage of Scanner, first reading a nextInt, and then twice a nextLine might cause an empty string, and that is always contained. You could take the second nextLine, or alternatively, use a BufferedReader, which is less error prone.
public static void display(){
System.out.println("You selected display a contact, choose an option :");
System.out.println("1. by the first name");
System.out.println("2. by the last name");
System.out.println("3. by the ID");
System.out.println("4. by the phone number");
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int str3 = Integer.parseInt(sc.readLine());
switch (str3) {
case 1:
System.out.println("Please enter the first name of the contact");
String fname = sc.readLine();
for (int i = 0; i < phoneBook.size(); i++) {
if (phoneBook.get(i).getFirstName().toLowerCase().contains(fname.toLowerCase())) {
displayContact(phoneBook.get(i));
}
}
break;
case 2:
System.out.println("Please enter the last name of the contact");
String lname = sc.readLine();
for (int i = 0; i < phoneBook.size(); i++){
if (phoneBook.get(i).getLastName().toLowerCase().contains(lname.toLowerCase())) {
displayContact(phoneBook.get(i));
}
}
break;
case 3:
System.out.println("Please enter the ID of the contact");
int id = Integer.parseInt(sc.readLine());
for (int i = 0; i < phoneBook.size(); i++) {
if (id == phoneBook.get(i)).getID()) {
displayContact(phoneBook.get(i));
}
}
break;
case 4:
System.out.println("Please enter the phone number of the contact");
int phnb = Integer.parseInt(sc.readLine());
for(int i = 0; i < phoneBook.size(); i++){
if(phnb == phoneBook.get(i).getPhoneNb()){
displayContact(phoneBook.get(i));
}
}
break;
}
System.out.println(" ");
System.out.println("If you want to go back at main menu press 1, else press 2 to quit.");
int str8 = Integer.parseInt(sc.readLine());
if(str8 == 1){
menu();
}
if(str8 == 2){
quit();
}
}
As an extra the switch statement.

what is the best way to use a for loop?

This program is a guessing game in which you input a letter between a and j and try to guess the randomly chosen answer. It works correctly, but I want to use a for loop to encompass all three guesses instead of writing them all out separately. Any suggestions on how to start this?
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
class Guess{
public static void main( String[] args ){
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your first guess: ");
Random r = new Random();
char i = (char)(r.nextInt(10) + 'a');
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your second guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your third guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
}
if(b!=i){
System.out.println("You lose. The letter was " +i+ ".");
}
}
}
Store the character the user should guess in a variable outside the loop.
Then inside the loop ask them to attempt guess number i+1 where i is the loop counter (or you can change to using a 1 based index).
If execution continues after the loop then it means they lost.
Here is an example:
import java.util.Random;
import java.util.Scanner;
class Guess {
public static void main(String[] args) {
int maxGuesses = 3;
System.out.println("I'm thinking of a letter in the range a to j. You have " + maxGuesses + " guesses. ");
Random r = new Random();
char i = (char) (r.nextInt(10) + 'a');
Scanner sc = new Scanner(System.in);
String[] guessDescription = { "First", "Second", "Third" };
for (int g = 0; g < maxGuesses; g++) {
// use predefined guess description for 1-3, otherwise a generic description that works for any number of guesses above 3
if (g < guessDescription.length) {
System.out.print("Enter your " + guessDescription[g] + " guess:");
} else {
System.out.print("Enter guess #" + (g + 1) + ":");
}
char b = sc.next().charAt(0);
if (b > i) {
System.out.println("Your guess is too high. ");
} else if (b < i) {
System.out.println("Your guess is too low. ");
} else if (b == i) {
System.out.println("You win! ");
return;
}
}
System.out.println("You lose. The letter was " + i + ".");
}
}
you can use a nested loop.
this part is basically the same, and can be in inner loop (of 3 iterations)
System.out.print("Enter your ... guess: ")
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
but the System.out.print("Enter your ... guess: ") is different every iteration. You can create const array of string with the strings {"first", "second", "third"} and access the correct string by the index of the loop (use format string here...)
Map your letters into a List<> or ArrayList<> then use for-each loop
Check this answer for a simple example of how to use for-each loop:
You just need to replace your line Enter your .... guess.
Based on i, you should keep a mapping like
{ 0:First,1:Second,2:Third}
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
List < String > strList = new ArrayList <String> ( );
strList.add("FIRST");
strList.add("SECOND");
strList.add("THIRD");
Random r = new Random();
char randX = (char)(r.nextInt(10) + 'a');
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your"+ strList.get(i)+ " guess: ");
char b = sc.next().charAt(0);
if(b==i){
System.out.println("You win! ");
return;
}
else
{
if(b>randX)
{
System.out.println("Your guess is too high. ");
}
else
System.out.println("Your guess is too low. ");
if ( b !=randX && i==2 )
{
System.out.println("You lose. The letter was " + randX + ".");
}
}
}
Here is a quick example with a loop to play again if the game is over
class Guess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random r = new Random();
char toGuess;
char yourGuess;
boolean playing = true;
boolean lost = true;
while(playing) {
toGuess = (char) (r.nextInt(10) + 'a');
System.out.println("NEW GAME");
System.out.println("========");
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for (int j = 0; j < 3; j++) {
switch (j) {
case 0:
System.out.print("Enter your first guess: ");
break;
case 1:
System.out.print("Enter your second guess: ");
break;
case 2:
System.out.print("Enter your third guess: ");
break;
default:
System.out.println("Something went wrong. Game is closing!");
System.exit(0);
break;
}
yourGuess = sc.next().charAt(0);
if (yourGuess > toGuess) {
System.out.println("Your guess is too high.");
} else if (yourGuess < toGuess) {
System.out.println("Your guess is too low. ");
} else if (yourGuess == toGuess) {
System.out.println("You win! ");
lost = false;
break;
}
}
if(lost==false){
System.out.println("Sorry, you lost!");
}
System.out.print("Do you want to play again? (y=yes | n=no): ");
if(!sc.next().equals("y")){
playing=false;
}
}
}
}

Hangman, exits the game without getting the user response (loop)

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Categories

Resources