简体   繁体   中英

basic java: scanning files, arrays

Extremely new to programming. I have looked up a lot of similar programs but I get lost trying to relate them to this program. Just looking for a simple push in the right direction

Scanners are handy for reading input that is stored in a file. For this exercise, create a file called "c:\\aaa\\numbers.txt" that contains the following data:

  1.2   2.3  3.4  4.5
  2.0   3.0  4.0  5.0
  6.0   7.0  8.0  9.0

Read each line, convert the numbers in each line to doubles, and print each row of numbers and their total.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.List;

public class ScanningFiles {
    public static void main(String[] args) throws FileNotFoundException {

        Scanner numbersFile = new Scanner(new File("numbers.txt"));

        List<String> tokens = new ArrayList<>();

        while (numbersFile.hasNextLine()) {
            tokens = numbersFile.nextline();
            // put each value into an array with String#split();
            String[] numStrings = line.split(" ");
            // parse number string into doubles
            double[] numbs = new double[numString.length];

            for (int i = 0; i < nums.length; i++) {
                nums[i] = Double.parseDouble(numStrings[i]);
            }

        }
        numbersFile.close();

        System.out.println(numbers);
    }
}

That is what I have tried so far, but to be honest that is way over my head. I'm getting very lost

A gentle push:

  1. Use scanner to read it all as one block
  2. Look into the String.split() method to break them up
  3. Look into Double.parseDouble() to convert them
  4. Add them together and print the results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM