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
How to Set a Timeout on a Spring Boot Rest API
What Happens When Base and Derived Classes Each Have Variables With the Same Name
Illegal Character When Trying to Compile Java Code
Convert Localdatetime to Localdatetime in Utc
Could Not Read Json: Can Not Deserialize Instance of Hello.Country[] Out of Start_Object Token
Calling Method That Exists in Child Classes But Not in Parent Class
How to Test for Blank Line With Java Scanner
Javax.Xml.Bind.Unmarshalexception: Unexpected Element (Uri:"", Local:"Group")
Bootstrap.Yml Not Loading in Spring Boot 2
Regular Expression (Regex). How to Ignore or Exclude Everything in Between
Resttemplate: How to Send Url and Query Parameters Together
Knowing Which Java.Exe Process to Kill on a Windows Machine
How to Check Whether a Field Exists or Not in Mongodb
Maven Build Cannot Find Symbol When Accessing Project Lombok Annotated Methods,
How to Convert Date Which I Got from Firebase Server as Am Getting Error Date
Mockito How to Mock Only the Call of a Method of the Superclass