Jonardan Cena
Jonardan Cena

Reputation: 383

reading the file from right side in java

Suppose the file sample.txt content is:

1 casual 1 3 5 5
2 casual 5 2 5 3
3 casual 1 5 4 3
4 dress 4 5 4 4
5 athletic 2 4 5 2

Now, what i want is to take the last four numbers and possibly multiply each with four more numbers that will be taken from the user as:

Take the last four digits of the first line i.e. 1 3 5 5 then:

input1x1 + input2x3 + input3x5+ input4x5 = result.

Can anyone help me on how to achieve this, this is the code i have written till now which can read the file and then convert into list. :

import java.io.*;
import java.util.*;

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

    FileReader n = new FileReader("sample.txt");
    Scanner in = new Scanner(n);

    ArrayList<String> lines = new ArrayList<String>();

    while (in.hasNext()) {
        lines.add(in.nextLine());
    }

    in.close();
    System.out.println(lines.get(1));
    // for (int i = 0; i<lines.size()-1; i++) {
    //     System.out.println(lines.get(i));
    // }

}
}

Upvotes: 2

Views: 112

Answers (2)

AirlineDog
AirlineDog

Reputation: 528

After you run your above code, this gets 4 integers from user and multiplies them with your files numbers

    Scanner sc = new Scanner(System.in);
    for(int i = 0; i < lines.size(); i++) {

          String[] number = lines.get(i).split(" ");
          int result = 0;
          for (int x=2;x<=5;x++) {
          result += Integer.parseInt(number[x]) * sc.nextInt();
          }

          System.out.println(result);
        }

Upvotes: 1

Reto H&#246;hener
Reto H&#246;hener

Reputation: 5808

for(int i = 0; i < lines.size() - 1; i++) {
  String line = lines.get(i);
  String[] parts = line.split(" ");
  int result = 0;
  result += Integer.parseInt(parts[2]) * 1;
  result += Integer.parseInt(parts[3]) * 3;
  result += Integer.parseInt(parts[4]) * 5;
  result += Integer.parseInt(parts[5]) * 5;
  System.out.println(line + " -> " + result);
}

Upvotes: 2

Related Questions