Taking input an arbitrary number of times - java

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.

Related

Save Integers with the Scanner class

I have a quick question about the Scanner class.
I had an idea to make a simple program that starts to count all the numbers I write in, but if it goes over a limit it should stop.
This is not the problem....
The problem is that the FIRST number you write in should be the number that tells the program how many numbers it will be counting.
For an example.
When the program starts, I will write in for example :
3
100
234
546
Sum: 880.
and the output should be the sum of 100+234+546.
The number 3 in the beginning just told the program that it is 3 numbers that it should read. I don't understand how to make the first number the number that tells the program how many numbers it should be in the input before it starts to count.
If you are using Java 8, you can do something like this:
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();
use this code
void yourMethod()
{
int sum=0;
Scanner scan = new Scanner(System.in);
int conut=scan.next();
for(int i=0;i<count;i++)
{
sum=sum+scan.next();
}
}
Store the first number in a variable called counter or similar, and then execute a loop (for, while) for counter times, in each iteration you will read the next number and sum them. The algorithm seems very straightforward to create code from it.
How about:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
//your logic
count--;
}

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.

Adding unknown number of numbers to arraylist

I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.
public class InsertionSort {
public static void main(String[] args){
System.out.println("Enter the numbers to be sorted now: ");
ArrayList<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
while(usrIn.hasNextInt()) {
unsortNums.add(usrIn.nextInt());
System.out.println(unsortNums); //TODO: Doesn't stop here
}
sortNums(unsortNums);
}
}
Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.
Let me know if I left anything out that I need to include.
Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.
Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.
As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.
When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:
System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
int i = usrIn.nextInt();
while(i != -999) {
unsortNums.add(i);
i = usrIn.nextInt();
}

How to break a loop in Java where the input size is not previously specified?

I need to input n numbers, store them in a variable and make them available for later processing.
Constraints:
1. Any number of SPACES between successive inputs.
2. The count of inputs would be UNKNOWN.
3. Input set should not exceed 256KB and should be between 0<= i <=10^18
Example Input:
100
9
81
128
1278
If I understand your question, then yes. One way, is to use a Scanner, and hasNextDouble()
Scanner scan = new Scanner(System.in);
List<Double> al = new ArrayList<>();
while (scan.hasNextDouble()) { // <-- when no more doubles, the loop will stop.
al.add(scan.nextDouble());
}
System.out.println(al);
if you're input is all coming in on one line like in your text, you could do something like:
import java.util.ArrayList;
public class Numbers
{
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList<Double>();
String[] inputs = args[0].split(" ");
for (String input : inputs)
{
numbers.add(Double.parseDouble(input));
}
//do something clever with numbers array list.
}
}

JAVA My two-dimensional array scanned from a text file prints without the first column

I am working on a lab for school so any help would be appreciated, but I do not want this solved for me. I am working in NetBeans and my main goal is to create a "two-dimensional" array by scanning in integers from a text file. So far, my program runs with no errors, but I am missing the first column of my array. My input looks like:
6
3
0 0 45
1 1 9
2 2 569
3 2 17
2 3 -17
5 3 9999
-1
where 6 is the number of rows, 3 is the number of columns, and -1 is the sentinel. My output looks like:
0 45
1 9
2 569
2 17
3 -17
3 9999
End of file detected.
BUILD SUCCESSFUL (total time: 0 seconds)
As you can see, everything prints correctly except for the missing first column.
Here is my program:
import java.io.*;
import java.util.Scanner;
public class Lab3
{
public static void main(String[] arg) throws IOException
{
File inputFile = new File("C:\\Users\\weebaby\\Documents\\NetBeansProjects\\Lab3\\src\\input.txt");
Scanner scan = new Scanner (inputFile);
final int SENT = -1;
int R=0, C=0;
int [][] rcArray;
//Reads in two values R and C, providing dimensions for the rows and columns.
R = scan.nextInt();
C = scan.nextInt();
//Creates two-dimensional array of size R and C.
rcArray = new int [R][C];
while (scan.nextInt() != SENT)
{
String line = scan.nextLine();
String[] numbers = line.split(" ");
int newArray[] = new int[numbers.length];
for (int i = 1; i < numbers.length; i++)
{
newArray[i] = Integer.parseInt(numbers[i]);
System.out.print(newArray[i]+" ");
}
System.out.println();
}
System.out.println("End of file detected.");
}
}
Clearly, there is a logical error here. Could someone please explain why the first column is invisible? Is there a way I can only use my rcArray or do I have to keep both my rcArray and newArray? Also, how I can get my file path to just read "input.txt" so that my file path isn't so long? The file "input.txt" is located in my Lab3 src folder (same folder as my program), so I thought I could just use File inputFile = new File("input.txt"); to locate the file, but I can't.
//Edit
Okay I have changed this part of my code:
for (int i = 0; i < numbers[0].length(); i++)
{
newArray[i] = Integer.parseInt(numbers[i]);
if (newArray[i]==SENT)
break;
System.out.print(newArray[i]+" ");
}
System.out.println();
Running the program (starting at 0 instead of 1) now gives the output:
0
1
2
3
2
5
which happens to be the first column. :) I'm getting somewhere!
//Edit 2
In case anyone cares, I figured everything out. :) Thanks for all of your help and feedback.
Since you do not want this solved for you, I will leave you with a hint:
Arrays in Java are 0 based, not 1 based.
As well as Jeffrey's point around the 0-based nature of arrays, look at this:
while (scan.nextInt() != SENT)
{
String line = scan.nextLine();
...
You're consuming an integer (using nextInt()) but all you're doing with that value is checking that it's not SENT. You probably want something like:
int firstNumber;
while ((firstNumber = scan.nextInt()) != SENT)
{
String line = scan.nextLine();
...
// Use line *and* firstNumber here
Or alternatively (and more cleanly IMO):
while (scan.hasNextLine())
{
String line = scan.nextLine();
// Now split the line... and use a break statement if the parsed first
// value is SENT.

Categories