===========================================================================
I just realized my mistake.
Instead of writing
xvar = string.substring(i,i + 1);
yvar = string.substring(count - 1 - i, count - i);
I wrote
xvar = string.substring(i,i + 1);
yvar = string.substring(count - 1 - i);
I was not aware that you had to "end" a substring, I used this answer. Considering the upvotes it has, I was wondering if someone could explain why it didn't work in my case . https://stackoverflow.com/a/40213223/14488701
==========================================================================
I was given an assignment that asks me to check if a word is a palindromes, but I am not allowed to use charAt.
This was the program I wrote using charAt
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
a = a.replaceAll("\\s","");
String string = a.toLowerCase();
int count = string.length();
int counter = 0;
for (int i = 0; i < count; i++)
if (string.charAt(i) != string.charAt(count - i - 1)) {
System.out.print("");
}
else {
counter++;
}
if (counter >= count) {
System.out.println("This is a palindrome.");
}
else {
System.out.println("This is not a palindrome.");
}
}
}
I am a bit confused on how to use substrings to solve this though.
This is what I tried so far. It does not work.
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
a = a.replaceAll("\\s","");
String string = a.toLowerCase();
int count = string.length();
int counter = 0;
String xvar = " ";
String yvar = " ";
for (int i = 0; i < count; i++) {
xvar = string.substring(i, i + 1);
yvar = string.substring(count - 1 - i);
if (xvar.equals(yvar)){
counter++;
}
else {
System.out.print("");
}
}
if (counter == count) {
System.out.println("This is a palindrome.");
}
else {
System.out.println("This is not a palindrome.");
}
}
}
So if I have the word pop and i =0, xvar would be "p", and yvar would also be "p".
for i=1, xvar would be "o", and yvar would also be "o".
For i =2 xvar would be "p" and yvar would also be "p".
Since there are 3 matches, I'm confused as to why I am getting the output "This is not a palindrome"
I was hoping someone could help my find my errors! Thanks.
Aucun commentaire:
Enregistrer un commentaire