I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:
90.0
71.5
87.9
95.0
98.1
Code:
File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();
//create array
double[] array = new double[12];
//variable to increment
int u = 0;
//loop to put data into array
while(gradesFile.hasNextDouble())
array[u] = gradesFile.nextDouble();
u += 1;
gradesFile.close();
A. As #hnefatl said you need to group statements in the loop,
while(<condition>) {
statement1;
...
statementN;
}
otherwise only next one executes.
while(<condition>) statement1;
...
B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.
So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.
If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextLine()) {
String line = gradesFile.nextLine();
array[u] = Double.parseDouble(line);
u += 1;
}
gradesFile.close();
or if you'd like to use nextDouble() you do not mix it with nextLine()
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextDouble()) {
array[u] = gradesFile.nextDouble();
u++;
}
gradesFile.close();
You can simply scan the double value in your file and store in the array as below
Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;
try {
scan = new Scanner(file);
//Scan while the file has next double value
while(scan.hasNextDouble())
{
//Save the double value read from text file and store to array
array[i] = scan.nextDouble();
i++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
To print what you have stored in your array
for(int y = 0; y < array.length;y++)
{
System.out.println(array[y]);
}
Related
I am trying to read a file in Java and store it into an array. Now the problem is that the file has the following structure. I will give 2 example files below:
input file structure
<number of lines>
<line number> <value>
.
.
.
<line number> <value>
input1.txt
5
1 34
2 19
3 43
4 62
5 36
input2.txt
4
1 10.3430423
2 -34.234923
3 -100.39292
4 22
As you can see the file starts with the number of lines(e.g 4 or 5). In the normal input text I have there are more than 100000 lines.
So my code basically grabs the user input, opens the file, create an array size and an array of that size. Now I am stuck on reading the next line and adding the values to my elements array. The line number should not be added into the array. Now as you can see, my elements array is declared as String. Is it possible to actually read the file, get the type of the value and create an array of that type? I think it could save from converting from string to int or double or floating?
Below is my code:
public static void main(String args[]) throws NumberFormatException, IOException{
String inFile; //Input file name.
int filterSize; //Filter size (odd integer >= 3).
String outFile; //Output file name.
int arraySize;
String[] elements;
int index = 0;
//Scanner to take input file name, filter size and output file name.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter your keyboard input as follows: <data file name> <filter size(odd int >= 3> <output file name>");
//Assigning values to variables.
inFile = keyboardInput.next();
filterSize = keyboardInput.nextInt();
outFile = keyboardInput.next();
//Reading file into array using BufferReader
BufferedReader fileInput = new BufferedReader(new FileReader(inFile));
arraySize = Integer.parseInt(fileInput.readLine()); //Get Array Size
elements = new String[arraySize];
while(fileInput.readLine() != null){
elements[index] = fileInput.readLine();
index += 1;
}
}
Any help is appreciated. Thanks.
Try doing it like this:
Scanner sc = new Scanner(new File(inFile));
arraySize = sc.nextInt();
elements = new String[arraySize];
while(sc.hasNext())
{
sc.nextInt();
elements[index] = sc.next();
index += 1;
}
You create new Scanner and you can than read integers, booleans and so on, without any converting. Because you don't need line of current number, you just read that number and that is it. You don't need to save it anywhere. Then the next number/string you must save at elements[index]. That's it
Go stream-based:
Files.lines(pathToFile).skip(1) // skip the line counter. Don't trust input
.map(line -> line.replaceFirst("\\d+", "")) // remove digits at the start
.collect(Collectors.toList()); // collect it into a list
You can Store it into an array with .toArray() anyways
But actually you should do that with a try-with-resources:
try (Stream<String> lines = Files.lines(pathToFile).skip(1)) {
elements = lines.map(line -> line.replaceFirst("\\d", "")).collect(Collectors.toList());
} catch (IOException e) {
// sensible handling...
}
Read the number, never use it.
File file = new File("input1.txt");
Scanner in = new Scanner(file);
int lines = in.nextInt();
int []a = new int[lines];
for(int i = 0; i < lines; i++)
{
int fakeNumber = in.nextInt();//read it but never used it
a[i] = in.nextInt();
}
You could also use in#hasNextLine() also.
The real question here is how to get rid line number and get the value besides it.
double[] array = .... // initialize your array
int v = 0;
while(file.readLine() != null){
// your array
array[v++] = Double.parseDouble(file.readLine().split(" ")[1]);
}
I am trying to parse information from a text file in the following format:
WarningGeotask: 0, 1
The first word is a keyword for a certain object to create at the coordinate location given in the numbers that follow it. Here is what my loop looks like currently:
// Open file and scan for a line
File f = new File("Simulation.Configuration");
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
// Parse each line with a temporary scanner
String line = s.nextLine();
Scanner s2 = new Scanner(line);
// Get keywords from the file to match to variable names
String keyword = s2.next();
//...Multiple if statements searching for different keywords...
else if (keyword.equals("WarningGeotask:")) {
int xCoord = s2.nextInt();
int yCoord = s2.nextInt();
WarningGeotask warningGeotask = new WarningGeotask(xCoord, yCoord);
s2.close();
continue;
}
}
However, this code doesn't work properly. In fact, String xCoord = s2.nextInt() throws an error. I can do s2.next() and print out s2.nextInt() which returns 1. But I'm not sure what I'm doing wrong with Scanner to get 0 and 1 set to two different variables. Thanks for the help!
EDIT: The String variables xCoord and yCoord are supposed to be int - my fault.
The thing is that Scanner#nextInt() returns a numerical value (to be exact: a value of type int), which you try to assign to a String variable.
So instead of:
String xCoord = s2.nextInt();
String yCoord = s2.nextInt();
try:
int x = s2.nextInt();
int y = s2.nextInt();
You can do this using split()
when you read the lines, make it as Comma-separated value :
while (s.hasNextLine()) {
String line = s.nextLine().replace(":",",");
String[] data =line.split(",");
//...Multiple if statements searching for different keywords
else if(data[0].equals("WarningGeotask:")){
WarningGeotask warningGeotask = new WarningGeotask(Integer.parseInt(data[1].trim()), Integer.parseInt[data[2].trim());
}
try this
sc.useDelimiter("\\D+");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
I'm cating a file using the cat text-file | Java my-program on my terminal
the result when I print the lines after i store it into a array results in null
can someone explain why?
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
int index = 0;//create index to increment through array
while(scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
count++;
}
if(count < BUFSIZE){
stringArray = new String[count];
}
else{
stringArray = new String[BUFSIZE];
}
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
{
stringArray = expandArray(stringArray,BUFSIZE);//call method to increase array length
}
stringArray[index] = line2;//store line into array at given index
index++;//increment index
}
/*while(sorted){
sorted = false;
for(int i = 0; i < stringArray.length-1; i++){
if(stringArray[i].compareTo(stringArray[i+1]) > 0){
temp = stringArray[i];
stringArray[i] = stringArray[i+1];
stringArray[i+1] = temp;
sorted = true;
}
}
}*/
for(int i = 0; i < stringArray.length; i++){
System.out.println(stringArray[i]);
}
}
}
private static String [] expandArray(String [] array, int extend){
String newArray [] = new String[array.length+extend];//create new array with given array and int as length to extend
//for loop to copy data from old array into new created array
for( int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
return newArray;//return newly created array
}
}
the program bubble sorts the array of strings. If I read in the file through Scanner file its fine, but why I cat it doesn't. The expand array method is to dynamically expand the array every-time it reaches max capacity. Thank you
The following is wrong:
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
Basically, each scanner grabs the System.in stream, but streams can only be read once. You should change your code to use only one scanner, and then only use it once.
When you wrote the program to use a file, the Scanner would actually open two streams to the file so that it can be read twice, but this won't work when all you have is one stream.
EDIT:
Here is a version where you use only one Scanner (and thus one stream) :
Scanner scan = new Scanner(System.in);//create new scanner object
int count = 0;
stringArray = new String[BUFSIZE];
while (scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
if (count >= stringArray.length) {
//call method to double array length
stringArray = expandArray(stringArray, stringArray.length);
}
stringArray[count] = line;
count++;
}
// Shrink array to required size
String[] temp = stringArray;
stringArray = new String[count];
System.arraycopy(temp, 0, stringArray, 0, count);
Please note I didn't test it, but this is conceptually how you could do it.
The other alternative is to use an ArrayList<String> which will automatically expand and shrink.
Scanner scan = new Scanner(System.in);
List<String> list = new LinkedList<>();
while(scan.hasNext()) list.add(scan.next());
scan.close();
Collections.sort(list);
for(String line : list) System.out.println(line);
lol
UPDATE #JBert:
System.out.println(StringUtils.join(Ordering.<String>natural().sortedCopy(IOUtils.readLines(System.in)), "\r\n"));
looool
In this code
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
you are doing something if index is greater than the length of the array, but no doing anything otherwise.
I am having some difficulty declaring an array on the text in a file. In other words, I am trying to store the information on a file into an array as double[] and displaying the array with the enhanced for loop. The file just contains 12 decimal numbers. Any help will be greatly appreciated. Below is a snippet of my code:
// create inFile2 variable
Scanner inFile2 = new Scanner("/Users/timothylee/KeyWestHumid.txt");
// while statment for inFile2
while(inFile2.hasNext()){
// create double reader
double num2 = inFile2.nextDouble();
double[] humidity1 = new double[num2];
// for-each loop for displaying humidity
for(double humidity : humidity1){
// display array for humidity
}
}
The enhanced for loop is only useful for looking at the values in an array/collection already. Java doesn't do pass by reference so your double humidity field is just a copy, not a reference to the array.
You need to do something like
for(int i = 0; i < humidity1.length; i++)
humidity1[i] = inFile2.nextDouble();
Scanner s = new Scanner(new File("C:\\usr\\a.txt"));
double[] darray = new double[12];
int i=0;
while (s.hasNextDouble()) {
darray[i++] = s.nextDouble();
}
for (double d : darray) {
System.out.println(d);
}
I gave it a try now, there are two issues in your code:
First by using Scanner this way:
Scanner s = new Scanner("Bla.txt");
Will return 'Bla.txt' when calling s.nextLine(). To get the file content you need to pass a File object to your scanner like this:
Scanner inFile2 = new Scanner(new File("/Users/timothylee/KeyWestHumid.txt"));
The second issue is on how to fill those values into an array, here is my approach on doing so:
public static void main(String[] args){
try {
//Initiate the scanner to read the files content
Scanner scanner = new Scanner(new File("D:\\temp\\backup_branch\\test.txt"));
//Have something to care about array dimensions (see note about this in the answer!)
List<Double> numbersFromFile = new ArrayList<Double>();
while(scanner.hasNext()){
double num2 = scanner.nextDouble();
//add every number
numbersFromFile.add(num2);
}
//Have it as array
//Object[] vals = numbersFromFile.toArray();
//double d = (double) vals[0];
//System.out.println(d);
//Print it
for(Double d : numbersFromFile){
System.out.println(d);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Note: I seem to have a lack when it comes to generics and primitive types so dont rely on the generic part of this solution. It is more about to show you that you first want to fill your array with data and then use the new for-loop to iterate over an existing array.
i am writing a code that reads input from a file and writes into another after some processing ofcourse.
now, my input file is,
4
0 1
0 2
0
0 3
3
0
0
0
E
and what i need to do is copy elements on left to an array in first column and elements on right to second column.
i used scanner but it does not recognize end of line.
help me!!!!
this is what i tried.
i tried copying lines and then modifying it.
for (i = 0; i < size; i++) {
if (!f1.hasNext(endPage)) {
String temp1 = f1.next();
String temp2 = f1.next();
int a[] = new int[4];
a[0] = (int) temp1.charAt(temp1.length() - 1);
a[1] = (int) temp2.charAt(temp1.length() - 1);
a[2] = (int) temp1.charAt(temp1.length() - 2);
a[3] = (int) temp1.charAt(temp1.length() - 2);
scales[i].weightOnLeft = a[0];
scales[i].weightOnRight = a[1];
scales[i].left = scales[a[2]];
scales[i].right = scales[a[3]];
}
}
Try this way:
Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
String data = input.nextLine();
}
Try to use the Scanner to read line by line and then split(on space, in your case) your line to get the tokens.
Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
String line = f1.nextLine();
String[] tokens = line.split(" "); // Splitting on space
// Do what you want with your tokens
// Since not all lines have equal no. of tokens, you need to handle that accordingly
}
Try like this below:-
In your first column it will store on array[0] and second column value will store on array[1]. Also for second column you need to check the condtion as written below. Please follow:-
File file=new File("/Users/home/Desktop/a.txt");
String[] aa=new String[2];
try {
Scanner sc=new Scanner(file);
while (sc.hasNextLine())
{
String ss=sc.nextLine();
aa=ss.split("\\s");
//it will store left column value in this index
System.out.println("aa[0]"+aa[0]);
if(aa.length>1)
{
//it will store right column value in this index
System.out.println("aa[1]"+aa[1]);
}
}
}