Reputation: 709
This file reads from a text file that has only one line:
7319812227725338960527291316
and the output is:
Reading input values from text.txt
731
981
222
772
533
89
60
527
291
316
Question is How does the program give this output? I don't know how it stores 3 digits in each array cell?
I also noticed that when I copy content of the txt file to Word, it pastes this
7319812227725338960527291316
into a column:
731
981
222
772
533
89
60
527
291
316
The text file is from my teacher. But when I create my own text file and place a number like 123 456 789 the output makes sense since numbers in txt file are separated by space and hence each number will be assigned to an array cell.
import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.io.File;
public class test{
public static void main(String[] args){
Scanner s;
if (args.length > 0){
try{
s = new Scanner(new File(args[0]));
} catch(java.io.FileNotFoundException e){
System.out.printf("Unable to open %s\n",args[0]);
return;
}
System.out.printf("Reading input values from %s.\n",args[0]);
}else{
s = new Scanner(System.in);
System.out.printf("Enter a list of non-negative integers. Enter a negative value to end the list.\n");
}
Vector<Integer> inputVector = new Vector<Integer>();
int v;
while(s.hasNextInt() && (v = s.nextInt()) >= 0)
inputVector.add(v);
int[] array = new int[inputVector.size()];
for (int i = 0; i < array.length; i++){
array[i] = inputVector.get(i);
System.out.println(array[i]);
}
}
}
Upvotes: 0
Views: 96
Reputation: 9645
The problem is the line ending character. Your machine's text editor doesn't understand the line breaks inserted by your professors program. But your java program does check for other OS's line endings. That's why your Java program can actually pick up the right numbers. I'm sure you can open the text file from your teacher with a different text editor (like Sublime) that will allow you see and convert file with different line ending characters
Upvotes: 3