Read multiple lines STDIN Java - java

i need to read multiple lines from stdin in java.
For example i need to read this two lines:
A A A H
A E D A H
and give an answer for each line.
I have made this but i can stop the while
Scanner sc = new Scanner(System.in);
Posicao p;
int max[][] = new int[4][], j = 0;
String com;
String[] b;
char[] c;
while(sc.hasNextLine()){
p = new Posicao();
com = sc.nextLine();
b = com.split(" ");
c = new char [b.length];
for(int i = 0;i<b.length;i++) c[i] = b[i].charAt(0);
p.comando(c);
max[j++] = p.retorna();
}

if (com.isEmpty()) {
break;
}

You could check what the user inputs and exit on empty input or the word "exit":
/*This would go in your while loop, after you process the input*/
if (com.equals("") | com.equals("exit")) {
System.out.println("Exiting...");
break;
} else
System.out.println("Still in loop");

Ideally you need to modify this part while(sc.hasNextLine()) to break the loop. Do you know any of the below values?
Number of lines
Any special char using which you can find end of input

Read each line using Scanner.nextLine() method and use String.split() or StringTokenizer to read tokens from each line. (see the example below) :
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine())
{
String[] tokens = scanner.nextLine().split("\\s");
System.out.println(Arrays.toString(tokens));
}
scanner.close();}

Related

how to stop while loop when taking input without words: "exit" etc

I have to take inputs until EOF (white space or end of line). For example:
1
2
3
4
// end of taking input
I'm using Scanner to take inputs. I tried this solution.
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
ArrayList<String> password = new ArrayList<>();
String input;
while (!(input = sc.nextLine()).equals("")) {
password.add(input);
}
boolean[] lengthValidation = lengthCheck(password);
boolean[] passwordContainCheck = containCheck(password);
print(lengthValidation, passwordContainCheck);
}
I can't use this, due to uri does not take it variant of answer
while(true) {
String input = sc.nextLine();
if (input.equals(""))
break;
}
I have to take inputs until EOF (white space or end of line).
Try the following. One entry per line. Terminate with an empty line. You can store them in a list and use them when the loop terminates.
Scanner input = new Scanner(System.in);
String v;
List<String> items = new ArrayList<>();
while (!(v = input.nextLine()).isBlank()) {
items.add(v);
}
System.out.println(items);
Maybe this is what you are looking for, Scanner take input until it meets an empty line, then the loop stop
Scanner sc = new Scanner(System.in);
ArrayList<String> password = new ArrayList<>();
String input;
while (true) {
input = sc.nextLine();
if (input.equals("")) break;
password.add(input);
}

problem is while loop is not ending in taking input paragraph using system.in in Java

I am having problem in taking a hole paragraph as input in java using System.in and storing it in an array. but problem is with while loop is not ending and program stuck in the loop. i have tried many methods but loop is not ending.
Scanner sc = new Scanner(System.in);
ArrayList < String > al = new ArrayList<>();
System.out.print("Please Enter Paragraph + \n");
while (!(sc.equals(null))) {
al.add(sc.next());
}
Scanner sc = new Scanner(System.in);
String para = sc.nextLine();
int x = 0;
while (para != null) {
if (sc.hasNextLine()) {
ParaArray[x] = para;
para = sc.nextLine();
x++;
} else {
para = null;
}
}
sc is a Scanner object. When you compare sc with null, you will never get true because sc could never be null. Also, your code seems to have a lot of errors. Your question is also unclear. Please provide a proper question...
-Thanks
Tejan Gandhi
Dt: 29th July (After reading your comment):
There are 2 parts of code, one which scans characters and another scans lines.. Because the first "while" loop compares sc (which is a Scanner object) it can never be null and loop can never end.. So instead of doing
sc.equals(null)
sc.hasNext()
Tell me if that works for you.
when you use "sc.hasNextline",you should put"Scanner sc= new Scanner(System.in); " before your judgment statement,just like this:
int num = 0;
while (true) {
System.out.println("Please input a number");
Scanner sc = new Scanner(System.in);
if (sc.hasNextDouble()) {
num = sc.nextDouble();
} else {
System.out.println("It is not a number,please try again!");
System.out.println("============================");
}
}
After your first loop you have already an array of paragraphs so why it is not clear why you need a second loop.
I've also put the scanner in a try () because Scanner is Closeable so it is closed at the end.
import java.util.ArrayList;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
ArrayList<String> al = new ArrayList<>();
while (true) {
System.out.println("Please Enter Paragraph + \n");
String readLine = sc.nextLine();
if (readLine.length() == 0) {
break;
}
al.add(readLine);
}
System.out.println("result:"+al);
}
}
}

Scanning input into char array Java

I was trying to store input as
5
3DRP 3QEW
8AQW 9ADA
I want to read that input in as a copy paste and put it. I've tried this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userNumber;
userNumber = scan.nextLine();
String[] tokens = userNumber.split("[ ]");
System.out.println(tokens[1]);
for(int i = 0; i < tokens.length;i++) {
System.out.println(tokens[i]);
}
scan.close();
}
My goal is to basically read that input in as a copy paste into the IDE or through a file a .txt and then store every single character besides whitespaces into a char array that is 1d or 2d.
From what I understand, you want to read 3 lines from the console, remove all the white spaces from that text and store it as a char array.
If that is the case, here is how you could do that:
int numberOfLinesToRead = 3;
try(Scanner sc = new Scanner(System.in)){
StringBuilder buff = new StringBuilder();
while(numberOfLinesToRead-- > 0){
String line = sc.nextLine();
String noSpaces = line.replaceAll("\\s", "");
buff.append(noSpaces);
}
char[] characters = buff.toString().toCharArray();
System.out.println(Arrays.toString(characters));
}catch (Exception e) {
e.printStackTrace();
}

Java Scanner delimiter and System.in

I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}

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