Question about Scanner and String values
Hello! I'm a relative beginner and this is my first post, and it's somewhat of an obscure question, so hopefully I've got all my wording right!
I'm working on a program, and in this program I have a Scanner object set up using an empty delimiter. The input is a date (e.g. 1997), so I have 4 String objects set to receive input so that I can use each numeral of the date seperately.
Code :
Scanner scanner = new Scanner(System.in);
String delim = new String();
scanner.useDelimiter(delim);
String a = new String();
String b = new String();
String c = new String();
String d = new String();
System.out.print("Please enter a year: ")
a = scanner.next();
b = scanner.next();
c = scanner.next();
d = scanner.next();
Now, I had assumed that if, for example, I entered a 3-character string for my input, my fourth String, d, would remain "null" but that is not in fact the case. When concatenated with other strings it seems to be a newline character of some sort. When checked for length it has a length of 1. But when compared to System.getProperty("line.seperator") or "\n" it returns false, using both the .equals method of the String class and the boolean == operator. I'd really like to know what the value that is being assigned to this String is (or rather how to represent that value in Java) so that I can use it for the sake of comparison in my program.
If anyone can help, that'd be great. Or, if you think I need to further clarify what I'm trying to ask, please let me know! Thanks!
Re: Question about Scanner and String values
May be the following will shed some light:
Code :
import java.util.Scanner;
public class Foo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String delim = new String();
scanner.useDelimiter(delim);
// (A)
String a = new String();
String b = new String();
String c = new String();
String d = new String();
// (B)
System.out.print("Please enter a year: ");
a = scanner.next();
b = scanner.next();
c = scanner.next();
d = scanner.next();
// (C)
System.out.println("-->" + d + "<--");
System.out.println("\n".equals(d));
System.out.println((int)d.charAt(0));
System.out.println((int)"\n".charAt(0));
// (D)
String e = scanner.next();
System.out.println("\n".equals(e));
// (E)
String real = System.getProperty("line.separator");
System.out.println("d+e is the real line separator: " + (d+e).equals(real));
String bogus = System.getProperty("line.seperator");
System.out.println("d+e is the bogus line separator: " + (d+e).equals(bogus));
}
}
(I'm assuming a Windows OS)
I was going to comment on all of that, but am too lazy! Ask if anything is unclear. Notice I didn't bother to initialise e with "new String()" as it seems a bit redundant to give a variable a value and then assign it another.
I think I would read the whole line and use the string method toCharArray() for a task like this.