I'm pretty much a complete newbie when it comes to Java. I've dabbled a bit in python and VB.net, and that's about it.
I'm trying to write a program in java that literally reads the user's input and displays it back to them with this code:
import java.util.Scanner; public class InputTesting { public static void main( String[] args ) { Scanner input = new Scanner ( System.in ); String str1; System.out.println("Input string: "); str1 = input.nextString(); System.out.println( str1 ); } } And I get the error:
InputTesting.java:13: error: cannot find symbol str1 = input.nextString(); ^ symbol: method nextString() location: variable input of type Scanner 1 error Can someone tell what why it's not compiling? Thanks!
14 Answers
input.nextString(); There is no method called nextString in the Scanner class. That's why you're getting the error cannot find symbol.
Try
input.nextLine(); // If you're expecting the user to hit enter when done. input.next(); // Just another option. import java.util.Scanner; public class InputTesting { public static void main( String[] args ) { Scanner input = new Scanner ( System.in ); String str1; System.out.println("Input string: "); str1 = input.next(); System.out.println( str1 ); } } You may use one of input.nextXXX() as detailed in Scanner javadoc. to resolve compiler error
in your case
you may use input.nextLine(); get entire line of text.
By Default whitespace delimiter used by a scanner. However If you need to scan sequence of inputs separated by a delimiter useDelimiter can be used to set regex delim
public static void main(String[] args) { try (Scanner input = new Scanner(System.in);) { input.useDelimiter(";"); while (input.hasNext()) { String next = input.next(); if ("DONE".equals(next)) { break; } System.out.println("Token:" + next); } } } Input
1a;2b;3c;4d;5e;DONE; Output
Token:1a Token:2b Token:3c Token:4d Token:5e Just be cautious while scanning decimal and signed numbers as scanning is Locale Dependent
You need to rather use method nextLine(). This methods prints entire line. By using next() it will print only one word in your sentence.