Dj Barrington Dj Barrington - 17 days ago 6
Java Question

my input from "Scanner" is not being recorded? Returns nothing

I am making a small project for computer science. I am making a code to test if a string input is a palindrome, or a phrase that is the same forward and backwards, Ex. "racecar" = "racecar" when read backwards.

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a palindrome or something...: ");
String myLine = keyboard.nextLine();
Palindrome test = new Palindrome();
test.setPaly(myLine);
System.out.println(test);


my scanner goes into a variable 'myLine' which I throw into my other piece of code in another file, called by a toString through
System.out.println(test)
from the last block of code:

public void setPaly(String setp)
{
in = setp;
boolean b1 = true;
int x = 0;
while(x<in.length())
{
b1 = Character.isLetter(x);
if (b1 != false)
{
paly = paly + in.substring(x, x+1);
}
x++;
}
}


see, 'paly' and 'in' are both pre-initialized, but that isn't my problem... my question comes here: 'paly' never actually get overwritten. Why is this? I don't understand at all... so please explain a little more thoroughly than just giving me an answer.

I am using codeboard.io to make this, and as such, you can look at my full code (in case It actually isn't part of these chunks of code at all) here:
Link: (https://codeboard.io/projects/33278?view=21.1-2.0)

Answer

This is a very simple problem, perhaps even a simple typo. Your line

b1 = Character.isLetter(x)

is, I presume, attempting to check if the value at x in the string is a character. However, it does not do that, for a few reasons.


x is an int. If we check the docs we find the following:

isLetter(int codePoint)
Determines if the specified character (Unicode code point) is a letter.

When you pass isLetter the int (x, which will count from 0 to some reasonably low value), it simply checks if those code points are letters. The first Unicode letter is at U+0041, and indeed if you enter a sting longer than 41 characters into your program, it'll start returning values.

I imagine what you are looking for is

b1 = Character.isLetter(in.charAt(x));

This is a simple conflation of index values with values at an index, a problem that would be normally caught precompile, but isn't because of the extra methods of isLetter.

Because it never returns as the codepoint being a letter (until you get past the initial control characters and gubbins), the condition is simply never true, and thus doesn't modify paly.

Comments