This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 5 months ago.
I have made a java code to play hangman game. I have given the user 15 chances to guess the word and once the user has guessed the correct answer it should execute the if statement but it does not. I have tried to solve this problem many times but it is never working. I would appreciate it if you could tell me the problem and give a suitable solution without making much change in my code.
My code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
ArrayList<String> ans = new ArrayList<String>();
for (char i : ask.toCharArray()){
ans.add("_");
}
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
String input = in.next();
char alt = input.charAt(0);
int x = 0;
for (char i : word.toCharArray()){
if(alt == i){
ans.set(x, input);
}
x++;
}
for (String i : ans){
System.out.print(i);
}
int y = 0;
ArrayList<String> answer = new ArrayList<String>();
for (char i : word.toCharArray()){
answer.add("_");
}
for(char i : word.toCharArray()){
String alternate = String.valueOf(i);
answer.set(y, alternate);
y++;
}
if (ans == answer){
System.out.println("\nyou win");
break;
}
System.out.println("\n"+ans);
System.out.println(answer
);
}
}
}
Due to so many many unsuccessful attempts my code may have some unnecessary lines which are making the long.
when you use == it compares whether these two reference variables are pointing to the same object or not.
if you want to compare their content then you should use the equals() method which compares the content of the object, not the object itself.
use ans.equals(answer) instead of ans== answer
Try using equals() method instead of ==.
if (ans.equals(answer)){
Related
So I've tried adding count ++ in multiple places in my code along with researching some way to allow multiple inputs to no avail. Am I missing something on placement or would I need to rewrite the code entirely for what I am wanting to accomplish? Is this not a boolean match situation? Very lost and sorry if this is a noob question. Appreciate the input.
Scanner scanner = new Scanner(System.in);
System.out.println("Insert any State Capital");
String currentInput = scanner.nextLine();
boolean match = false;
String [] capitals = stateCapitals[1];
for (String capital:capitals) {
if (capital.equalsIgnoreCase(currentInput)) {
match = true;
break;
}
}
if (match) {
System.out.println ("Correct");
}
else
System.out.println ("incorrect");
}
}
Problem and what I've tried is above. Also, apologies on formatting if it's messed up. First time using stack overflow.
Please see the below code and let me know if this solves your issue.
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<>();
ArrayList<String> capitalList = new ArrayList<>(List.of("Delhi","Kabul","Dhaka"));
for (int i = 0; i < 5; i++)
{
String currentInput = scanner.nextLine();
inputList.add(currentInput);
}
int correct_response_count = 0;
int wrong_response_count = 0;
for (int i = 0; i < inputList.size(); i++)
{
if (capitalList.contains(inputList.get(i)))
{
correct_response_count++;
}
else
{
wrong_response_count++;
}
}
System.out.println("The correct count of answers is: " + correct_response_count);
System.out.println("The wrong count of answers is: " + wrong_response_count);
}
}
Input
India
Delhi
Australia
Kabul
Bangladesh
Output
The correct count of answers is: 2
The wrong count of answers is: 3
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
When I try to use a while loop it won't follow the conditions I set in the while. Like if I put while s1 != "n") it will continue even if s1 = n. It does the opposite when I try to use while s1 == "y") and it very irritating. I'm trying to make a factorial calculator that prompts the user if they would like to keep going or stop.
Here's the full code:
package factorial;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
int factorial = 1;
int number = 6;
int i = 1;
String s1 = "y";
Scanner keyboard = new Scanner(System.in);
while(s1 != "n") {
System.out.println("Enter an N:");
number = keyboard.nextInt();
while(i <= number) {
factorial *= i;
i++;
}
System.out.println("Factorial = "+factorial);
System.out.println("Would you like to continue? (y/n)");
s1 = keyboard.next();
}
keyboard.close();
System.out.println("Have a nice day!");
}
}
As #Debabrata says use equals for strings, replace:
while(s1 != "n") {
with
while(!s1.equals("n")) {
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am fairly new to Java and am in need of help with my If/Else statement. Basically I want to make it so that if the person types in n or no do one thing, or if the person puts in y or yes, do another thing, and if the person doesn't put in n, no, yes or y than do a different thing. But no matter what the user puts in, it acts as if they did not put in n, no, yes or y. How can I fix this?
This is my code so far:
public class Main
{
public static void main (String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
String [] charName = {"John", "Bob", "Sam"};
Random random = new Random();
int charNameChoice = random.nextInt(charName.length);
System.out.println("Random char selected: " + charName[charNameChoice]);
System.out.println("Y N Question1");
System.out.println("You can input y, yes, n or no");
String questionOneAnswer = userInputScanner.nextLine();
if (questionOneAnswer == "n" || questionOneAnswer == "no")
{
System.out.println("I disagree");
}
else if (questionOneAnswer == "y" || questionOneAnswer == "yes")
{
System.out.println("I agree");
}
else
{
System.out.println("Invalid");
}
}
}
You should use equals to compare String values, like stringVar.equals("something").
Better yet, reversing it "something".equals(stringVar) prevents Nullpointerexceptions.
== compares the pointers, which are almost never equal (unless you're comparing String constants).
This question already has answers here:
Creating hangman game without arrays [closed]
(3 answers)
Closed 9 years ago.
Logic:
This is how the output should look like. http://prntscr.com/1is9ht i need to find the index of guess in the orginalString. If that's true then it should replace the question mark at the index with the character read in the string guess. After that it should take out that char from the string "abcdefghijklmnopqrstuvwxyz".
If originalString doesn't contain guess than it should only take out that char from the string "abcdefghijklmnopqrstuvwxyz" I looked up this question on google and found a bunch of codes, they were all using arrays or something that I have not learned in the classes. So please don't use arrays. I am stuck at the if else statement. Is there any way to solve this problem without using Arrays.
int count=1;
while (count<=24){
Scanner keyboard = new Scanner(System.in);
int length;
String originalString;
String guess;
String option= "abcdefghijklmnopqrstuvwxyz";
String questionmarks;
System.out.println("Please enter a string");
originalString=keyboard.nextLine();
length=originalString.length();
questionmarks = originalString.replaceAll(".", "?");
System.out.println("Original String: "+originalString);
System.out.println("Guessed String: "+questionmarks);
System.out.println("Characters to choose from: "+option);
System.out.println("Please guess a character");
guess=keyboard.nextLine();
if (originalString.contains(guess)){
count++;
}
else{
option.replace(guess, "_");
count++;
System.out.println(option);
}
Please suggest me some code that doesn't implement array concept for my problem,
Any help will be appreciated
A few things that I noticed from a cursory glance:
.replace() returns a String, it will not modify option unless you do:
option = option.replace(guess, "_");
Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder to have a String that's initialized to all -. Then when someone guess a correct letter, you can replace the - with the guess.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess, if you've determined that the character at position i should be replaced by guess, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}