Why won't while loops find a palindrome in java? - java

i dont know if i am just doing this wrong, but using eclipse ill run it and enter a word but it won't return anything. i suck at coding so please help.
import cs1.Keyboard;
public class Palindrome
{
public static void main (String[]args)
{
System.out.print("Enter a word: ");
String w = Keyboard.readString();
int a = 0;
char n = w.charAt(a);
char j = w.charAt(w.length()-1);
while(a < j);
{
if (j!=n)
System.out.println("This word isnt a palindrome... try again.");
if (j==n)
{
j--;
a++;
}
System.out.println("This is a palindrome!");
}
}
}

Try writing
char j = w.charAt(w.length() - a);
and, when incrementing a in the while loop, update the indexes
n = w.charAt(a);
j = w.charAt(w.length()-1);
Also, make sure Keyboard.readString() returns a String. Try using Scanner.

Related

what to revise so that the final word can be print

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.

getting an error in my palindrome java program

I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}
For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}
Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
reversing the string first iterating the halfway
comparing the reversed string with the original using Arrays.equals() method.
There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for loop, as you saw you were getting an error. This was fixed by setting the initial i to the length minus 1, changing the loop condition to i >= 0, and using i-- to subtract 1 from i each loop.
These changes to the loop were made so that the character starting from the last position in the String is the first one being return by s.charAt(i) so you can reverse the String. I think you were attempting to do something along these lines to add the characters starting from the end to a String.
I also changed s1 = s + s.charAt(i) to s1 = s1 + s.charAt() so the correct String is being appended. (This should probably be StringBuilder however).
s and s1 now have the initial condition of "" instead of nothing.
And finally you cannot compare String equality with ==, it must be s1.equals(s).
Test Run:
Enter your string
racecar
This is Palindrome

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

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);
}

Creating a program that will give the number of A's both lower and upper case in the user entered string (java)

Alright, so here is my dilemma. Unfortunately my Java teacher does not teach how to start the projects in class, nor does he tell us where to find the information to start the program. This is my first programming course, so I'm still trying to learn a few things.
So, lets get to the point, he wants it to look like this:
This program is written by Ben Barcomb
Enter a String: Alaska
Number of A: 3
//End of program
That is it. I just don't know where to start. Any help would be greatly appreciated!
This is what I have right now. The program ends after I enter Alaska.
import java.util.Scanner;
public class P4_BenjaminBarcomb
{
public static void main(String[] args)
{
System.out.println("This program is written by Benjamin Barcomb\n");
Scanner kb = new Scanner(System.in);
int counter = 0;
System.out.print("Enter a String: ");
String word = kb.next();
for (int i = 0; i < word.length(); i++) {
if (word.substring(i, i+1).equalsIgnoreCase("a"))
counter++;
}
}
}
If you loop through the length of the string, you can check to see whether each letter is an "A".
For example,
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i+1).equalsIgnoreCase("a")) counter++;
}
you can also do like this:
int count=0;
String s ="Alaska";
for(char ch : s.toCharArray()){
if(ch=='A' || ch=='a'){
count++;
}
}
System.out.println("Number of A: "+count);
An example is this:
import java.util.Scanner;
public class Junk {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = Keyboard.nextLine();
for (int i = 0; i < str.length(); i++){
if (str.substring(i, i+1).equalsIgnoreCase("a")){
count++;
}
}
System.out.println("Number of A: "+count);

Categories

Resources