I'm getting some weird output when running (seemingly simple) code. Here's what I have:
import java.util.Scanner;
public class TestApplication {
public static void main(String[] args) {
System.out.println("Enter a password: ");
Scanner input = new Scanner(System.in);
input.next();
String s = input.toString();
System.out.println(s);
}
}
And the output I get after compiling successfully is:
Enter a password:
hello
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=5][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q8\E]
Which is sort of weird. What's happening and how do I print the value of s
?
If you have tried all the other answers, and it still hasn't work, you can try skipping a line:
Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);
input.next();
String s = input.toString();
change it to
String s = input.next();
May be that's what you were trying to do.
You could also use BufferedReader:
import java.io.*;
public class TestApplication {
public static void main (String[] args) {
System.out.print("Enter a password: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String password = null;
try {
password = br.readLine();
} catch (IOException e) {
System.out.println("IO error trying to read your password!");
System.exit(1);
}
System.out.println("Successfully read your password.");
}
}
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
Source: Stackoverflow.com