How to Take Input as String With Spaces in Java Using Scanner

How to take input as String with spaces in java using scanner

Your code work fine. I just add little modification:

package practise;

import java.util.Scanner;

public class scanccls {

public static void main(String[] args) {

System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name="";

name+=scan.nextLine();
scan.close();

System.out.println("Your name is :"+name);

}

}

Java - Scanner doesn't read string with space (Solved)

String t = "Chuck Norris";

t.matches("[a-zA-Z ]+")

Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com

how to allow spaces in input java

Please use in.nextLine();

import java.util.Scanner;

public class Yes {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
....
}
}

check for valid user input string and read the string with spaces using scanner in java

  • hasNext("[a-zA-Z]+") only checks if there is a token matching your expression, not if an entire line is available.

  • next() gets the next token from the scanner, not next line.

  • No real use for Scanner in this scenario.

This will work:

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));  // Optionally add a charset as 2nd parameter.
String street;
while (true) {
System.out.println("Please enter a valid street name>> " );
try {
String line = r.readLine();
// Accept a line with alphabetic characters delimited with space.
if (line.matches("[A-Za-z ]+$")) {
street = line;
break;
}
} catch (IOException e) {
// Handle broken input stream here.
street = "";
e.printStackTrace();
break;
}
}
System.out.println(street);


Related Topics



Leave a reply



Submit