what to revise so that the final word can be print - java

I'm still learning Java and me and my classmate are working on this assignment code game hangman. We have a problem in the part printing the original word, because we want the word to be hidden, but we need the word to be printed, not hidden on the final output. What can we revise in our code to make it print properly??
import java.util.Scanner;
public class GameHangman {
public static void main(String[] args) {
System.out.println("Welcome! To the HANGMAN game.");
System.out.println("Guess the word by guessing each letter.");
System.out.println("LET'S START!");
String[] words = {"superman","batman","spiderman"};
int t = words.length;
int x, y, miss;
String w;
char l, c='y';
Scanner input = new Scanner(System.in);
while (c=='y')
{
x = (int)(Math.random()*(t));
w = words[x];
char[]chars = w.toCharArray();
var hidden = new char[w.length()];
for(int i = 0; i < hidden.length; i++)
{
hidden[i] = '*';
}
boolean z = false;
int count = 0;
miss = 0;
while(!z)
{
System.out.print("\n(guess) Enter a letter ("+new String(hidden)+"): ");
l = input.next().charAt(0);
y = 0;
for(int i = 0; i < hidden.length; i++)
{
if(chars[i]==l)
{
y++;
if(hidden[i]=='*')
{
hidden[i]=l;
count++;
y++;
}
}
}
if(y==1)System.out.println("\nOOPS!("+l+") already present, try other letters.");
else if (y==0)
{
miss++;
System.out.println("\nYIKES!("+l+") is not in the word, guess again.");
}
if(count==hidden.length) z = true;
}
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
System.out.println("You were wrong "+miss+" tries.");
System.out.print("\nDo you want to continue with another game word? "
+ "\nEnter yes or no: ");
c = input.next().charAt(0);
}
}
}
in this part, we print our final word
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
and this is what we are getting output. we need to print with not being hidden.

Here are two methods to convert your char array hidden into a String for printing out.
// First option: Create a String object
String str1 = new String(hidden);
System.out.println("\nGreat!! You guessed the word("+str1+")!!!");
// Second option: Using valueOf method
String str2 = String.valueOf(hidden);
System.out.println("\nGreat!! You guessed the word("+str2+")!!!");
Alternatively, you can also print your String variable w and avoid calling these methods.

Related

Using a for loop to call a character method multiple times. The for loop will then convert each character to a string

The output should look like the attached screenshot. I am stuck on the very last step. Using a for loop to call the getCharacter method 10 times and converting the characters to a string using the Character.toString() method.
``
public static void main(String[] args) {
int count = countNumbers();
countPlay(count);
String word = getCharacter();
stringOf10(word);
}
public static double getRealNumber(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a real number, one that has a decimal point: ");
double realNumber = sc.nextDouble();
return realNumber;
}
public static int countNumbers(){
int count = 0;
do{
if (getRealNumber() == -1.0)
break;
count++;
} while(true);
System.out.println("The count is " + count);
return count;
}
public static int countPlay(int count){
int exponent = 4;
double result = 0;
result = Math.pow(count, exponent);
System.out.println(count + "^" + exponent + " is " + result );
return count;
}
public static char getCharacter(){
Scanner input = new Scanner(System.in);
System.out.println("You will be asked to enter 10 characters.");
System.out.print("Enter a character: ");
char character = input.next().charAt(0);
return character;
}
public static char stringOf10(String word){
char i = getCharacter();
i = Character.toString(word) ;
for (i = 0; i < 10; i++){
}
return word;
}
}
``
Consider the following block of code which will run in the main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = "";
//Print the instructions before the loop
System.out.println("You will be asked to enter 10 characters.");
//request characters inside the loop
for (int i = 0; i < 10; i++){
System.out.print("Enter a character: ");
word += input.next().charAt(0);
}
//print the result (or return from a method)
System.out.println("The word is: " + word);
//return word;
}
Besides the corrections in comments, note how we create a local variable word, and simply update/append that inside the for loop word += input.next().charAt(0);.
You can easily move this code to fit your needs and return the value to be printed:
public static void main(String[] args) {
//Call the method to get our word and save the result
String result = stringOf10();
//Print the result
System.out.println("The word is: " + result);
}
public static String stringOf10(){
//Creater a scanner once before the loop
Scanner input = new Scanner(System.in);
//Create a local variable to store the word as it is updated
String word = "";
//Print the instructions once before the loop
System.out.println("You will be asked to enter 10 characters.");
//Create a loop that will run 10 times "for (int i = 0; i < 10; i++)"
//The loop starts by creating an int that is 0 "int i=0"
//Each time the loop ends it will do "i = i+1"
//The loop will run until i is no longer less than 10 "i < 10"
//Once that happens the loop will end and the code after the loop will run
for (int i = 0; i < 10; i++){
//Dach time the loop will call this method and update the word
word += getCharacter(input);
}
return word;
}
public static char getCharacter(Scanner input){
//Each time this method is called we prompt the user to enter a character
System.out.print("Enter a character: ");
//We then return the character to the previous method
return input.next().charAt(0);
}

only checks first and last character

I am new to java and am trying to create a palindrome word program, to check if the word backwards is the same.
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
String reversed = new StringBuffer(word).reverse().toString();
int len = word.length();
for(int x = 0; x < len ; x++){
if(word.charAt(x) == reversed.charAt(x)){
System.out.println("True");
}else{
System.out.println("False");
}
}
}
Please excuse if I've done anything wrong, I have only started learning today.
My problem is :
With the current it outputs True for something such as "otto" which is a palindrome. But it also does True for "oplko" which isn't. So I know that it only checks the first and last letters but I thought that with the for loop it will go through each letter?
Can someone be kind enough to explain where I am going wrong and suggest how to fix it? The reason I am using a for loop is because the task is requiring me to do so.
You are very close to the solution. Since you have already reversed the string you can check if they are equal
new StringBuffer(word).reverse().equals(word);
Edit: Added one more solution for using loop
What you are doing in the loop is mostly correct. You are getting True for oplko is because you are not exiting the loop when the word.charAt(x) == reversed.charAt(x) condition fails. This can be fixed by
public static void isPalindromeWord() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
String reversed = new StringBuffer(word).reverse().toString();
int len = word.length();
for (int x = 0; x < len; x++) {
if (word.charAt(x) != reversed.charAt(x)) {
System.out.println("False");
return;
}
}
System.out.println("True");
}
there are a lot of ways to do what you want (including Anthony C's very elegant answer), but here is a simple fix to make yours work :
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
//you don't really need to get a reverse here
//String reversed = new StringBuffer(word).reverse().toString();
int len = (int)(word.length() / 2);//only check half (and not evnt the middle one for odd numbers
boolean isPalindrom = true;
for(int x = 0; x < len ; x++){
if(word.charAt(x) != word.charAt(word.length() - 1 - x)){
isPalindrom = false;
//at least one difference, this is not a palindrome
break;
}
}
if(isPalindrom)
System.out.println("True");//the for wasn't broken
else
System.out.println("False");
}
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next();
String reversed = input.next();
char c[]=word.toLowerCase().toCharArray();
char d[]=reversed.toLowerCase().toCharArray();
if(word.length() != reversed.length()) System.out.print("False ");
Arrays.sort(c);
Arrays.sort(d);
if(Arrays.equals(c,d)) System.out.print("True ");
else System.out.print("False ");
}
Just to describe where you have a mistake. You are writing in console on every step of loop, doesn't matter which result of comparing do you have.
boolean isPolindrom = true;
for(int x = 0; x < len ; x++){
isPolindrom = (word.charAt(x) == reversed.charAt(x)); //compare chars and store result into variable
if (!isPolindrom) { //if chars are different break a loop, because word is already not a polindrom
break;
}
}
System.out.println(isPolindrom); //output result
Solution from #AnthonyC is really better

Unable to accept two strings in first iteration but works fine during successive iterations

I'm scanning 2 strings during each iteration and storing it in s and t. Only during the first iteration, the first string that I scan is getting stored in t and not in s (I got to know this by debugging in eclipse). During successive iterations the piece of code works fine. I'm not able to understand what is going on during the first iteration. Please help me. Thanks.
import java.io.*;
import java.util.*;
public class ResidentInfo {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int i,n;
n = scan.nextInt();
for(i=0 ; i<n ; i++)
{
int sl,tl,j,k;
String s, t;
boolean flag = false;
s = scan.nextLine();
t = scan.nextLine();
sl = s.length();
tl = t.length();
char[] sa = new char[sl];
char[] ta = new char[tl];
sa = s.toCharArray();
ta = t.toCharArray();
for(j=0 ; j<sl ; j++)
{
for(k=0 ; k<tl ; k++)
{
if(sa[j]==ta[k])
{
flag = true;
break;
}
}
if(flag)
{
break;
}
}
if(flag)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
The first thing this code does is determine if the two strings' lengths are equal. If the strings' lengths are not equal, the code prints no. If the lengths are equal, the code then checks each character in the exact same index in the strings, to see if they are equal. If the characters at a specific index is not equal, the code breaks the loop and prints no. If all of the characters at each index are equal the code prints yes.
You asked a question about next() and nextLine().
Try: Question asked already.
Scanner scan = new Scanner(System.in);
System.out.print("enter a number: ");
int n = scan.nextInt();
for(int i=0; i < n; i++)
{
boolean flag = true;
System.out.print("enter something for s: ");
String s = scan.next();
System.out.print("enter something for t: ");
String t = scan.next();
if(s.length() == t.length())
{
for(int j = 0; j < s.length(); j++)
{
if(s.charAt(j) != t.charAt(j))
{
flag = false;
break;
}
}
if(flag)
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}
}
else
{
System.out.println("NO");
}

Java program keeps exiting program prematurely

I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()

trying to find a different way to write this code

I have wrote this code and now i'm practicing and i'm trying it to write it in a different or more efficient way. Basically this code asks the user to enter a word and the second player guesses the letters of the word with 6 tries and at the end there is one last chance to guess the whole entire word. Any suggestions on how i can write this code in a simple way?
static int NUM_OF_TRIES = 6;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
boolean a = true;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(0) == word.charAt(j)) {
System.out.println(" at position " + (j + 1));
a = false;
break;
}
}
if (a) {
System.out.println("Sorry not letter " + guess.charAt(0));
continue;
}
}
System.out.println("Enter your last guess: ");
String wordComp;
wordComp = keyboard.next();
if (wordComp.equals(word)) {
System.out.println("You got it!");
} else {
System.out.println("Sorry you lost!");
}
}
}
Well, here is a shorter version:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
int index = word.indexOf(guess.charAt(0));
if (index == -1)
System.out.println("Sorry not letter " + guess.charAt(0));
else
System.out.println(" at position " + (index + 1));
}
System.out.println("Enter your last guess: ");
String wordComp = keyboard.next();
if (wordComp.equals(word))
System.out.println("You got it!");
else
System.out.println("Sorry you lost!");
}
---First of all you'll have to ensure that
word.length <=guess.length
or you'll run into an exception.--- edit: that was obv not correct
Can't test right now bc I'm on my mobile, but as far as I can see, you'll run into problems if the word to guess has the same letter multiple times, since you're breaking out of the loop after finding the equal first letter.
As mentioned in comments, the comparison could be done by a method like
private static List<Integer> getLetterIndices(String word, char letter);
Then you won't need your boolean to indicate correct guesses, but a list of indices found
And of course you can do an object oriented approach instead of the static main method (not that it's faster to implement or better performance, just for practicing), perhaps something in the lines of this:
public class WordToGuess{
private Map<Character,List<Integer>> letter2indices;//...
public WordToGuess(String word){
parseIndices(word);
}
//parse indices of each letter to the map
private void parseIndices(String word);
public List<Integer> getLetterIndices(char letter);
}

Categories

Resources