Char array updating - java

I have been working on my hangman program for far to long and cannot figure out why it is not replacing the characters entered with the asterisks.
There are a lot of details I have not added so please do not sit here and judge that. I need someone to tell my why the character the user enters is not replacing the asterisks and If you know what I could do to fix it please tell me.
I'm struggling. I have edited my program to show you where I know the logic error is coming from however I do not know what the error is.
String hiddenWord = wordList[rand];
char[] asterisks = new char[MAXCHAR];
hideWord(hiddenWord);
System.out.println(Arrays.toString(hideWord(hiddenWord)));
numGuess( hiddenWord,asterisks);
public static char[] hideWord(String hiddenWord)
{
int wordLength = hiddenWord.length();
//int length = wordLength * 2;
char[] asterisks = new char[wordLength];
for(int i=0; i < wordLength; i++)
{
asterisks[i] = '*';
}
return asterisks;
}
public static void numGuess(String hiddenWord,char[] asterisks)
{
Scanner keyboard = new Scanner(System.in);
hideWord(hiddenWord);
int remAttempts = MAXGUESS;
int i = 0;
while(i < (hiddenWord.length()-1))
{
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
if(asterisks[i] == (hiddenWord.charAt(i)))
{
//attemtps == hiddenWord.charAt(i);
System.out.println("Nice job!");
remAttempts--;
}
i++;
}
}

Look at this code (I changed the formatting a bit):
while (i < hiddenWord.length() - 1) {
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
//...
i++;
}
You're asking for a letter, but you really request a String with at least the size + 1 that equals i: keyboard.next().charAt(i);. Therefore, if you write just a letter, then you'll get an Exception at the second iteration of that loop.
I guess what you meant was: keyboard.next().charAt(0);. This will return the first character of the given String.
If this doesn't solve the problem, then provide the whole Stacktrace and mark the line in your code, where the Exception occurs.

Related

unable to update the output

I am trying to write a code to play hangman and it is working correctly but every time when I input a character, it resets my output. Can someone please help.
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");
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (char i : word.toCharArray()){
if(input == i){
System.out.print(input);
continue;
}
System.out.print("_");
}
}
}
}
A small piece of the output:
______
hint: It is a fruit
Enter a character:
a
__a___
Enter a character:
o
o_____
Enter a character:
r
_r____
Enter a character:
n
___n__
Enter a character:
When I enter 'a' it prints it correctly but when I enter some other character it prints that character an not 'a'. Can somebody pls tell me what should I do to get the correct output.
It looks like you are not saving the string with the character added to the game, you are only printing it. You will probably want to do something like add the new character to the string variable _ask rather than printing as you go, then print after the for loop has run. Basically you are not storing the past rounds anywhere.
As mentioned in the other answer you need to remember the characters from previous attempts. This could for example be done like this:
String tempAsk = "";
for (char i : word.toCharArray()){
if(input == i){
tempAsk += i;
} else {
tempAsk += ask.charAt(i);
}
}
ask = tempAsk;
System.out.println(ask);
I think that,
In the loop for (char i : word.toCharArray()),
you should add the character to ask (or have another string variable named ans),
and then print ask at the end of the loop
because you are not updating the value of ask and printing the place of the character in the string,
and when the loop runs a second time it doesn't show the last character that u entered
plus you can have specific hints according to the fruit name using switch case
and maybe have an error pop up when the player enters the wrong character
You can use a character array to check what letters are present so far like so:
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];
// Create a character array to store the result so far
char[] result = new char[word.length()];
//Fill the array with _
Arrays.fill(result, '_');
System.out.println(new String(result));
System.out.println("hint: It is a fruit");
int numChances = 15;
for (int j = 1; j <= numChances; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (int i = 0; i < word.length(); i++) {
if(word.charAt(i) == input){
//update the array with user's correct response
result[i] = input;
}
}
// Check how we're doing so far. Make a string with the result
String untilNow = new String(result);
// Show user what we have so far
System.out.println(untilNow);
//Check if the user has guessed the word.
if(untilNow.equalsIgnoreCase(word)) {
System.out.println("You win...");
break;
}
}
}

Java: How to Count a Character in a String

I have to count the number of times that a character appears in a string.
I know this question has been asked previously. However, the solutions that I've seen use commands/techniques that I haven't yet covered in class.
Here is my code:
import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/
public class LetterCounter
{
public static void main(String[] args)
{
int i, length, count=0;
String input;
char letter1, letter2;
// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);
// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();
// Get a character from user
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);
//Determine the length of the string
length = input.length();
//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++)
{
letter2 = input.charAt(i);
if (letter1 == letter2)
{
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);
}
}
Here is the output from jgrasp:
----jGRASP exec: java LetterCounter
Enter a string: hello world
Enter a character: l
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(String.java:658)
at LetterCounter.main(LetterCounter.java:37)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
I don't understand the errors. Any and all help is appreciated.
Looks like you're just iterating for too long:
for (int i = 0; i <= length; i++) {
...
}
should be
for (int i = 0; i < length; i++) {
...
}
I noticed that you wrote this line of code:
if (letter1 == letter2)
{
count++
}
I'd avoid using count++, you may end up getting mixed with ++count sometime. Sticking with the following is always good
if (letter1 == letter2) {
count + =1;
}
Error is occurring in the below line of code -
for (i = 0; i <= length; i++)
Here Iteration is longer than input length [exceeds the range].
The revised code will be -
for (i = 0; i < length; i++)
Need anything more? Shoot me a comment please.
Hopefully, it will work fine.

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

Looping CharAt to convert a String to ASCII

Hi guys i made this
import java.util.Scanner;
//Creates a class
public class codeString {
public static void main(String[] arg) { //creates scanne/giving name
Scanner ImBack = new Scanner(System.in);
//print out "enter any String" and asks to put in data
System.out.print("Enter any String :");
String Word = ImBack.nextLine();
int ascii = (int) Word.charAt(0);
System.out.println(ascii);
System.out.println((char) Word.charAt(0));
}
}
But when i run it it converts only 1 letter, I know that i have to make a loop..
so then i went on google and made this
for (Word.charAt(0); Word = int; Word = Word) {
System.out.println("" + Word);
}
printing lots of errors, one of them was asking for toString, but it worked with out the toString for the one letter, so i know i did loop wrong 100%, could anyone help? and will i need a
length
in there?
You need something like this :
for (int i = 0; i < Word.length(); i++) {
System.out.println(Word.charAt(i));
}
Word.length() return to you the length of your word or text
Word.charAt(i) to get character by character
You can learn also the Oracle tutorials about Arrays and do...while Loop

Java - How do i make a string read and count amounts in another string (

I'm having trouble activating my counter++. So far s2 is able to read s1, but cannot count amount of occurrences. Any help would be appreciated. (I realize that I am working in the wrong string, but it helps me to create the solution here first and then send it to a second string, is this poor logic?)
Sorry for the dumb question I am very new at programming
//i need a scanner that reads what i write that scanner should count
occurrences of a char another scanner declared scanner a would ask " write something" string s. = nextline etc new scanner asks for a letter string s1 = next line blb that input = something int count = StringUtils.countMatches(s1); System.out.print(amount ) i
//
public class Task07 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("write something");
String text = s1.nextLine(); //reads user input value
Scanner s2 = new Scanner(System.in); // missing smth that limits length of s2
System.out.println("geb a letter");
String letter = s2.nextLine();
int counter = 0;
boolean found;
found = text.contains(letter);
if (found == true) {
counter++;
} else {
System.out.println(counter);
}
// could use counter from 6 here but need a way to tell counter
// that it should add +1 for every time something occurs in
// the other scanner
/*
Problems: text recognizer is boolean only
- doesnt activate counter
- doesnt activate counter based on X times occurence
- doesnt limit "letter" to only one char
-
*/
}
}
Basically a loop is the simple way to count character occurrences in a string. You would use something like
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == letter.charAt(0)) {
counter++;
}
}

Categories

Resources