How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace. Easy example from Scanner API: String input = “1 fish 2 fish red fish blue fish”; // \\s* means 0 or more repetitions of any whitespace character // fish is the pattern to find Scanner s = new Scanner(input).useDelimiter(“\\s*fish\\s*”); System.out.println(s.nextInt()); // prints: 1 System.out.println(s.nextInt()); // prints: … Read more

Using scanner.nextLine() [duplicate]

I think your problem is that int selection = scanner.nextInt(); reads just the number, not the end of line or anything after the number. When you declare String sentence = scanner.nextLine(); This reads the remainder of the line with the number on it (with nothing after the number I suspect) Try placing a scanner.nextLine(); after … Read more

What’s the difference between next() and nextLine() methods from Scanner class?

I always prefer to read input using nextLine() and then parse the string. Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line. A useful tool for parsing data from nextLine() would be str.split(“\\s+”). String data = scanner.nextLine(); String[] pieces = … Read more

Scanner vs. StringTokenizer vs. String.Split

They’re essentially horses for courses. Scanner is designed for cases where you need to parse a string, pulling out data of different types. It’s very flexible, but arguably doesn’t give you the simplest API for simply getting an array of strings delimited by a particular expression. String.split() and Pattern.split() give you an easy syntax for … Read more

How can I read input from the console using the Scanner class in Java?

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It’s really quite simple. Scanner sc = new Scanner(System.in); int i = sc.nextInt(); To retrieve a username I would probably use sc.nextLine(). System.out.println(“Enter your username: “); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); System.out.println(“Your username is ” … Read more

Scanner is skipping nextLine() after using next() or nextFoo()?

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself). Workaround: Either put a Scanner.nextLine call after … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)