how to scan multiple lines without print statement - java

'''
Scanner sc = new Scanner(System.in);
ArrayList<Integer> arrayIntegers = new ArrayList<Integer>();
System.out.print("#ofints: ");
String[] arrayStrings = new String [sc.nextInt()];
sc.nextLine();
for (int i = 0; i < arrayStrings.length; i++)
{
arrayStrings[i] = sc.nextLine();
}
'''
-How can this be done with using hasNext() method (breaks if space is entered) so there is no need for user prompt statement.
so e.g.:
1
2
3
Instead of:
#ofints: 3
1
2
3

The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default.
Check this (stop on enter "exit"):
Scanner sc = new Scanner(System.in);
String inputStr;
while (sc.hasNext()) {
inputStr = sc.next();
if (inputStr.equals("exit")) break;
System.out.println(inputStr);
}
P.S. The hasNextLine() method checks to see if there's another line in the input of the Scanner object, no matter if the line is blank or not.

Related

How can I get input validation with Java using Scanner with regex.Pattern and arrays

I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.
This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?
Here is the relevant chunk of code from my little app.
//These variables used during input validation
String tempName;
int tempGrade;
//These regex patterns are for input validation
//Names can be 1-15 letters and grades are 2 digits
Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
Pattern gradePattern = Pattern.compile("[0-9]{2,2}");
//Parallel arrays to hold last names and grades
String[] names = new String[5];
int[] grades = new int[5];
Scanner in = new Scanner(System.in);
try {
for(int i = 0; i<5; i++) {
System.out.println("Enter a name:");
tempName = in.nextLine();
System.out.println("Enter a grade:");
tempGrade = in.nextInt();
in.nextLine();
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
}
names[i] = tempName;
grades[i] = tempGrade;
}
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
tempName = in.nextLine(); //<-- add this.
}
Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.

Multiple Scanner Inputs (Java)

I am currently learning Java and had a question:
I know that using Scanner will allow me to receive input from the console, but how do I receive multiple inputs on one line, rather than just one input per line?
For example:
Enter input: 1 3 5
You don't need multiple scanners. one is more than enough
By an input like 1 3 5 you can read that as a whole line(string)
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
System.out.println(input1);
or just get integer by integer
int inputA1 = sc.nextInt();
int inputA2 = sc.nextInt();
int inputA3 = sc.nextInt();
System.out.println("--------");
System.out.println(inputA1);
System.out.println(inputA2);
System.out.println(inputA3);
You can use below function that will return you multiple inputs from scanner
public List<String> getInputs(String inputseparator)
{
System.out.println("You Message here");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
return line.split(inputseparator);
}
and you can use it like that
List<String> inputs = getInputs(" ");
//iterate inputs and do what you want to . .
You can use nextLine() method of scanner.Below is sample code.
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
//sample input: 123 apple 314 orange
System.out.println("Enter multiple inputs on one line");
String st = s.nextLine();
s = new Scanner(st).useDelimiter("\\s");
//once the input is read from console in one line, you have to manually separate it using scanner methods.
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}
}

Read a character followed by n number of integers like A 1 2 3 using Java's Scanner(System.in) object from the same line

I am unable to read A 1 2 3 from the same line, 1 2 3 can be read from one line but because of A in the start, scanner only reads A.
String command = "";
int numbers;
List<Integer> ints = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
command = scan.next();
while (scan.hasNextInt())
{
numbers = scan.nextInt();
ints.add(numbers);
}
scan.close();
I would use nextLine() (and hasNextLine()), split on one or more consecutive white-space characters (to create an array of tokens), set the command as the first token and then Stream the tokens - skip the first one (it's command) and collect to a List. Like,
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split("\\s+");
String command = tokens[0];
List<Integer> ints = Stream.of(tokens).skip(1)
.mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
System.out.printf("command = %s, ints = %s%n", command, ints.toString());
}

Scanner takes blank as input

I want to get two string inputs into a string array
String[] b = new String[n];
by using scanner but the scanner automatically takes blank value in
b[0].i.e. it skips the first loop.
Scanner scn = new Scanner(System.in);
int no = 0;
int n = scn.nextInt();
String[] b = new String[n];
for (int j = 0; j < n; j++) {
System.out.println("Enter the string");
b[j] = scn.nextLine();
}
the output occurs like
2
Enter
Enter
abc
can anyone suggest me why this problem occurs??
This is because nextInt() does not read the \n in your input. This is then read by your nextLine()
More explanation,
When you enter a number when prompted by the nextInt() call. You type a number and press Enter This makes your input look like this
10\n
nextInt() reads only the 10 and leaves out \n.
Then, your nextLine() reads only the \n.
This explains your output.
You can get the expected output by having an extra nextLine() after the nextInt().
See this for more information on it.

Java stop reading after empty line

I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}

Categories