I want to validate the user input which should consist of two digits between 1 and 3 separated by a space. So far, the example 2 2 is matched.
Is my regex or the use I'm doing of it with !sc.hasNext() wrong to begin with?
Scanner sc = new Scanner(System.in);
System.out.println("Enter Coordinates: ");
while (!sc.hasNext("[1-3]\\s[1-3]")) {
System.out.println("Please enter right coordinates!");
sc.next();
}
String userInput = sc.nextLine();
String[] stringCords = userInput.split(" ", 2);
for (int i = 0; i < stringCords.length; i++) {
System.out.print("[" + stringCords[i] + "]" + " ");
}
int ycord = Integer.parseInt(stringCords[0]);
int xcord = Integer.parseInt(stringCords[1]);
For example, if I enter 1 1 I get this. Instead, I would like to validate it as correct and go on without being stuck in the loop.
1 1
Please enter right coordinates!
Please enter right coordinates!
Whitespace is the issue here, by default Scanner is splitting on whitespace which returns 2 values instead of one, change the default delimiter using sc.useDelimiter("\n"); and it should work.
Here is the full code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\n");
System.out.println("Enter Coordinates: ");
while (!sc.hasNext("[1-3]\\s[1-3]")) {
System.out.println("Please enter right coordinates!");
sc.next();
}
String userInput = sc.nextLine();
String[] stringCords = userInput.split(" ", 2);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to code a program that allows to enter various words(step by step) until one types in "quit" .
I am having trouble stopping the loop (even with the word quit typed, it doesn't stop)
Using System.out.println(sum); I can check that the words are adding up, but it never stops..
((Summary : if(string == "quit") does not work and for (String end = "quit"; string!=end;) does not work ))
Sorry if its hard to read. its my second day coding :(
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
if (string == "quit")
{System.out.println("Ending system");
}
else{
for(String end = "quit"; string!=end; )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
String stringextra = scanner.nextLine();
if(stringextra == "quit"){break;}
string = stringextra;
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}}
Strings string and "quit" are not the same objects(as stored in the jvm) yet equal so checking with == will not work.
You need to use:
string.equals("quit")
see Object.equals() for more information
As pointed out in the other answer you need to use .equals() to compare strings. Also, your for loop is incorrect. A while loop is what is normally used in this case:
public class end_on_quit {
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while ( ! string.equals("quit") )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}
Easiest way to doing something like your code using do while so your code running until user write quit. I will give you simple example :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String stringextra = scanner.nextLine();
if (stringextra.equalsIgnoreCase("quit")) {
System.out.println("Bye bye");
System.exit(0);
} else {
do {
sum = sum + " " + stringextra;
System.out.println(sum);
System.out.println("Type in another word");
stringextra = scanner.nextLine();
} while (!stringextra.equalsIgnoreCase("quit"));
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
I hope this help you, good luck.
You should use equalsto compare strings. In this case for you example is better use while instead of for to loop.
When you use equalsIgnoreCase it means that is no matter if the word is upper case or lower case (is the same).
The application finishes when the user types "quit or ends or QUIT or ENDS"
Example:
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while (!string.equalsIgnoreCase("quit")) {
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
if (string.equalsIgnoreCase("ends")) {
string = "quit";
}
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
System.exit(0);
}
Output:
Type in a word
hi
Type in another word
this
Type in another word
an
Type in another word
example
Type in another word
ENDS
Ending system
Stopping... due to the word quit
all the words typed are hi this an example
Process finished with exit code 0
Simply do System.exit(0) after System.out.println("Ending system");
How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
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 " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now
This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I am writing some code but am unsure how to set it so users can only input certain letters for grade. (A,B,C,D,F)
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String Grade1;
String Grade2;
String Grade3;
String Grade4;
String Grade5;
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
System.out.println("Please enter leter grade one. \n");
Grade1 = in.next();
System.out.println("Please enter leter grade two. \n");
Grade2 = in.next();
System.out.println("Please enter leter grade three. \n");
Grade3 = in.next();
System.out.println("Please enter leter grade four. \n");
Grade4 = in.next();
System.out.println("Please enter leter grade five. \n");
Grade5 = in.next();
System.out.println("Your grades are ==>");
System.out.println(Grade1);
System.out.println(Grade2);
System.out.println(Grade3);
System.out.println(Grade4);
System.out.println(Grade5);
}
}
Variables should start with lowercase letter.
To ensure only valid data is entered, loop back and ask again if it's wrong.
Letter is spelled with 2 t's.
Use nextLine(), not next().
Easiest way to check valid text (for this case), is a regular expression, e.g.
String grade1;
do {
System.out.println("Please enter letter grade one: ");
grade1 = in.nextLine();
} while (! grade1.matches("[ABCDF]"));
Use this approach.
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String[] grades = new String[5];
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
for(int i = 0; i < grades.length; i++) {
System.out.println("Please enter letter grade " + i + "\n");
grades[i] = in.nextLine();
while(!grade[i].matches("[abcdfABCDF]")) {
System.out.println("Please enter a grade from A to F");
grades[i] = in.nextLine();
}
}
System.out.println("Your grades are ==>");
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}
}
I am having trouble coding a hw program that is made to generate test with multiple choice and essay questions. Everything works except my program skips lines when it goes to read a part of the essay class. I know it has to do with the scanner and scan.nextline, scan.nextInt and scan.next, etc but I am confused on how exactly to fix it.
Thank you for your help.
import java.util.*;
public class TestWriter
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String type=null;
System.out.println ("How many questions are on your test?");
int num = scan.nextInt ();
Question [] test = new Question [num];
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next ();
scan.nextLine ();
if (type.equals ("e"))
{
test [i] = new Essay ();
test [i].readQuestion ();
}
if (type.equals ("m"))
{
test [i] = new MultChoice ();
test [i].readQuestion ();
}
}
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1)+": "+ type);
test [i].print ();
}
}
}
here is the essay class
public class Essay extends Question
{
String question;
int line;
public void readQuestion ()
{
System.out.println ("How many lines?");
line = scan.nextInt ();
scan.next ();
System.out.println ("Enter the question");
question = scan.nextLine ();
}
public void print ()
{
System.out.println (question);
for (int i=0; i <line; i++)
System.out.println ("");
}
}
Using scan.nextInt() will generate the following problems
If your input is "5 5", nextInt() will get the next integer leaving the remaining " 5" of the buffer line. Of which the remaining " 5" will be caught by
type = scan.next();
In the class test writer:
System.out.println("How many questions are on your test?");
int num = scan.nextInt();
Question[] test = new Question[num]; for(int i=0; i<num; i++)
{
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
This will generate the issue as i have mentioned above.
To fix this you can either
a) Ensure that input is solely a number
b) Get the entire line like so String temp = scan.nextLine(); then convert it to a integer. This will you can play with the string and check if its the input you require i.e if the 1st letter / set of numerical digits is an e/m or an integer.
The problem with scan.nextInt() is that it only gets the next integer of the input line. If there are spaces after the input it was taken from i.e "5 5" it will grab only the next int 5 and leave " 5" behind.
Thus i would recommend using scan.nextLine() and manipulating the string to ensure that the input can be handled and verified and at the same time ensuring that you do not get confused of where the scanner is at.
You should use .next() / .nextInt() if you are handling an input with various parameters you want to specifically catch such as "25 Male Student 1234" in this case the code would be as such
int age = scan.nextInt();
String sex = scan.next();
String job = scan.next();
int score = scan.nextInt();
Your readQuestion function should be ...
public void readQuestion()
{
System.out.println("How many lines?");
line = scan.nextInt();
scan.nextLine();
System.out.println("Enter the question");
question = scan.nextLine();
}
It should be scan.nextLine(); to add an empty new line at the end
In your TestWriter.main() method what are you expecting at 3 line in following code:
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
scan.nextLine(); //LINE 3: What are you expecting user to enter over here.
the control flow will stuck at this point unless you enter something on the console.