read input by user seperated by line breaks, spaces etc - java

im struggling with the input part of the below question.
Question: The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
how do i read the input from the user which are separated by line breaks, spaces etc. how do i make sure the input stream doesnot exceed 256 KB?
and how do i make sure that a particular input will be the last value entered by the user so that the program and proceed for execution?
the input can be given in anyway, any number not exceeding 10^8,EX: first input can be given as say 1 and in the same line the second input can be given as 34 separated by 3 spaces from the first input. then 2nd line and the 3rd line are empty and again in the fourth line, there can a number say 225345 which is the 3rd input. so once all the inputs are given by the user, i have to take them, arrange them into one list or array and perform some operations on them.
example:
1427 0
876652098643267843
5276538
kindly help. thanks

This should do the trick if there is at least one space between each number
Scanner scanner = new Scanner(new File("data.txt")); // or new Scanner(System.in) for reading from command line.
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNext()) {
int number = scanner.nextInt();
if (number<0||number>1018)
break;
list.add(number);
}
scanner.close();
System.out.println(list);
Example: (data.txt)
145 358
94 2
13 1205 158 489
Output:
[145, 358, 94, 2, 13, 1205, 158, 489]

Use a java.util.Scanner to read the sequence of longs (because 10^18 > Integer.MAX_VALUE):
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong()) {
long number = scanner.nextLong();
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
To validate the input stream size you can reuse the CountingInputStream from Guava or Commons IO, or code your own. Note that, due to internal buffering in Scanner, you may end up reading more than 256 KB of input.
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) { ... }
Ensuring that a particular input will be the last value requires you to pick a delimiter. I'd use a number out of the acceptable input, say, -1:
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) {
long number = scanner.nextLong();
if (number == -1)
break;
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
Hope this helps.

Related

txt file with integers, strings and bulleted list (1.)

I have a txt file which has several rows like this
7. SSWAB 38 15 - 57
but I don't need all the values, just the String and the integers.
I would use nextInt for the Integers, but how can I deal with 1. and -?
Also there is the string, what is a useful nextString? Is next enough?
I have tried something like this, just using tokens, but nothing happens
scanner.next(); //7.
String s = (scanner.next()); //SAVES sswab
Integer n1 = scanner.nextInt(); //38
Integer n2 = scanner.nextInt(); //15
Integer n3 = scanner.nextInt(); //- is skipped, as next int is 57
You can use scanner.next(Pattern pattern) for matching these groups.
Try this regex
-?\d+\.?(\d+)?|\w+
Demo
It would catch all groups you mentioned plus fractional numbers and negative numbers.
Then you can use this regex in scanner
String text = "7. SSWAB 38 15 - 57 ";
Scanner scanner = new Scanner(text);
while(scanner.hasNext()) {
if(scanner.hasNext("-?\\d+\\.?(\\d+)?|\\w+")) {
System.out.println(scanner.next("-?\\d+\\.?(\\d+)?|\\w+"));
} else {
scanner.next();
}
}
This code catch all matching groups and skip others. Output
7.
SSWAB
38
15
57

How to read predefined number of lines from scanner input based on multiple conditions for the input line

I need to read maximum 10 lines, with each lines having only characters * and . also with other conditions like begin with * and length 10. the last line that should be read should have a line following it with the word END. I want to know if there is a better way to solve it than below. If I can check all the conditions within the while loop
Scanner keyboard = new Scanner(System.in);
int countLine = 0;
String line = "";
while (countLine < 10) {
line = keyboard.nextLine();
countLine++;
if (line.matches("[*.]+") && !line.equals("END") && line.startsWith("*") && line.length() < 10
) {
// do something
} else {
break;
}
}
keyboard.close();
One way you can do this is:
read the entire document into your application.
parse each (row/column) into arrayLists (so the first 10 lines of the document)
perform necessary calculations (still in the while loop).

Reading multiple lines from console in java

I need to get multiple lines of input which will be integers from the console for my class problem. So far I have been using scanner but I have no solution. The input consists of n amount of lines. The input starts with an integer followed by a line of series of integers, this is repeated many times. When the user enters 0 that is when the input stops.
For example
Input:
3
3 2 1
4
4 2 1 3
0
So how can I read this series of lines and possible store each line as a element of an array using a scanner object? So far I have tried:
Scanner scan = new Scanner(System.in);
//while(scan.nextInt() != 0)
int counter = 0;
String[] input = new String[10];
while(scan.nextInt() != 0)
{
input[counter] = scan.nextLine();
counter++;
}
System.out.println(Arrays.toString(input));
You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. At the end of both loops you need to readLine().
Scanner scan = new Scanner(System.in);
for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) {
scan.readLine(); // clears the newline from the input buffer after reading "counter"
int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray();
scan.readLine(); // clears the newline from the input buffer after reading the ints
System.out.println(Arrays.toString(input)); // do what you want with the array
}
Here for elegance (IMHO) the inner loop is implemented with a stream.
You could use scan.nextLine() to get each line and then parse out the integers from the line by splitting it on the space character.
As mWhitley said just use String#split to split the input line on the space character
This will keep integers of each line into a List and print it
Scanner scan = new Scanner(System.in);
ArrayList integers = new ArrayList();
while (!scan.nextLine().equals("0")) {
for (String n : scan.nextLine().split(" ")) {
integers.add(Integer.valueOf(n));
}
}
System.out.println((Arrays.toString(integers.toArray())));

How to use delimiters to ignore floats greater than 1?

So I'm reading in a two column data txt file of the following from:
20 0.15
30 0.10
40 0.05
50 0.20
60 0.10
70 0.10
80 0.30
and I want to put the second column into an array( {0.15,0.10,0.05,0.2,0.1,0.1,0.3}) but I don't know how to parse the floats that are greater than 1. I've tried to read the file in as scanner and use delimiters but I don't know how to get ride of the integer that proceeds the token. Please help me.
here is my code for reference:
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*;
class OneStandard {
public static void main(String[] args) throws IOException {
Scanner input1 = new Scanner(new File("ClaimProportion.txt"));//reads in claim dataset txt file
Scanner input2 = new Scanner(new File("ClaimProportion.txt"));
Scanner input3 = new Scanner(new File("ClaimProportion.txt"));
//this while loop counts the number of lines in the file
while (input1.hasNextLine()) {
NumClaim++;
input1.nextLine();
}
System.out.println("There are "+NumClaim+" different claim sizes in this dataset.");
int[] ClaimSize = new int[NumClaim];
System.out.println(" ");
System.out.println("The different Claim sizes are:");
//This for loop put the first column into an array
for (int i=0; i<NumClaim;i++){
ClaimSize[i] = input2.nextInt();
System.out.println(ClaimSize[i]);
input2.nextLine();
}
double[] ProportionSize = new double[NumClaim];
//this for loop is trying to put the second column into an array
for(int j=0; j<NumClaim; j++){
input3.skip("20");
ProportionSize[j] = input3.nextDouble();
System.out.println(ProportionSize[j]);
input3.nextLine();
}
}
}
You can use "YourString".split("regex");
Example:
String input = "20 0.15";
String[] items = input.split(" "); // split the string whose delimiter is a " "
float floatNum = Float.parseFloat(items[1]); // get the float column and parse
if (floatNum > 1){
// number is greater than 1
} else {
// number is less than 1
}
Hope this helps.
You only need one Scanner. If you know that each line always contains one int and one double, you can read the numbers directly instead of reading lines.
You also don't need to read the file once to get the number of lines, again to get the numbers etc. - you can do it in one go. If you use ArrayList instead of array, you won't have to specify the size - it will grow as needed.
List<Integer> claimSizes = new ArrayList<>();
List<Double> proportionSizes = new ArrayList<>();
while (scanner.hasNext()) {
claimSizes.add(scanner.nextInt());
proportionSizes.add(scanner.nextDouble());
}
Now number of lines is claimSizes.size() (also proportionSizes.size()). The elements are accessed by claimSizes.get(i) etc.

Taking input an arbitrary number of times

I am looking to solve a coding problem, which requires me to take the input an arbitary number of times with one integer at one line. I am using an ArrayList to store those values.
The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000.
It is the number written on your coin.
For example
Input:
12
2
3
6
16
17
My attempt to take input in Java:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNext()){
list.add(inp.nextInt());
}
However, when I try to print the elements of the list to check if I have taken the inputs correctly, I don't get any output. the corresponding correct code in C goes like this:
unsigned long n;
while(scanf("%lu",&n)>0)
{
printf("%lu\n",functionName(n));
}
Please help me fix this thing with Java.
(PS: I am not able to submit solutions in Java because of this )
You can do this one thing! At the end of the input you can specify some character or string terminator.
code:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt())
{
list.add(inp.nextInt());
}
System.out.println("list contains");
for(Integer i : list)
{
System.out.println(i);
}
sample input:
10
20
30
40
53
exit
output:
list contains
10
20
30
40
53
Can you do something like this:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt()){
list.add(inp.nextInt());
}
If there is some another value like character, loop finishes.

Categories