user2561683
user2561683

Reputation: 15

How to read tokens x and y

I started study Java from a book I found in the web. I solved many exercises, but I am stack in this one. My problem is, that I couldn't find an answer about how to tell the program that if you read "x" the next integer you find add to the sumx. If you read "y" the next integer you find add to the sumy. Below is the problem and my code.

Say that a text file looks like this:

x= 10
y= -45
y= 98
x= 13
x= 37
y= 36
x= -2

. . .

Each line starts with "x=" or "y=" but which of these it starts with follows no pattern. Each of these is followed by a space then a single integer. Nothing else follows the integer on a line.

Write a program that reads in this data file and computes the sum of the x values and the sum of the y values. Hint: use hasNext() and next() to read the "x=" and "y=" tokens and then use nextInt() to read the integer. You will also need the equals() method of String.

import java.util.Scanner;
import java.io.*;
class Separatesums {
    public static void main(String[] args) throws IOException {
        int sumx = 0, sumy = 0, num = 0;

        File file = new File("input.txt");
        Scanner scan = new Scanner(file);

        while (scan.hasNext()) {
            if (scan.hasNext.equals("x")) {
                num = scan.nextInt();
                sumx = sumx + num;
            } else {
                if (scan.hasNext.equals("y")) {
                    num = scan.nextInt();
                    sumy = sumy + num;
                }
            }
        }
        System.out.println("Sum x is: " + sumx + " Sum y is: " + sumy);
    }
}

Upvotes: 0

Views: 564

Answers (3)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Try this

 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
 public class Read {
 public static void main(String[] args) throws IOException {
    FileReader file=new FileReader("D:\\Test.txt");
    BufferedReader br=new BufferedReader(file);
    String str;
    int xSum=0;
    int ySum=0;
    while((str=br.readLine())!=null)
    {
        if(str.contains("x=")){
            xSum+=Integer.parseInt(str.split("=")[1].trim());
        }if(str.contains("y=")){
            ySum+=Integer.parseInt(str.split("=")[1].trim());
        }
    }
    System.out.println("Sum x is: "+xSum+" Sum y is: "+ySum);
}
}

Upvotes: 1

crand6
crand6

Reputation: 114

You have the right idea, but you have some syntax and logic errors. I don't want to solve this entirely for you, but here are some notes

  1. Cascading method calls still need parentheses after each method. It should be scan.hasNext().equals("x"), as opposed to `scan.hasNext.equals("x")

  2. When using cascading calls, think about the data type returned after each method. What data type does hasNext() return? Does it make sense to ask if that data type is equal to a given string?

  3. Remember that hasNext() does not consume any data from the file. You should only use it to see if there is any data to read, but if it is there, you have to use next() or some variant thereof to actually get the data. In a similar vein, be careful of reading too many times from the file (such as using 2 different next() calls to read in one single variable).

  4. equals("x") is looking for an EXACT match. There are other string methods available to see if a string starts with a sequence of characters, or you should use the exact pattern you are expecting to match (ie, "x=").

The goal of these exercises is to help you think like a programmer. Even if someone gives you working code, make sure you understand every single line in detail before you use it.

Upvotes: 2

Clark Kent
Clark Kent

Reputation: 1176

I think your scan.hasNext.equals("x") is incorrect. If you replace it with scan.next().equals("x=") things could improve. Also, you're scanning twice. If your first scan fails, your next if-statement will cause you to scan ahead one more line.

The following would work:

import java.util.Scanner;

public class x {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int exes = 0;
    int whys = 0;
    while (scan.hasNext())
    {
      String line = scan.next();
      if (line.equals("x="))
        exes+=scan.nextInt();
      else
        whys+=scan.nextInt();
    }
    System.out.println("X: " + exes);
    System.out.println("Y: " + whys);
  }
}

Upvotes: 3

Related Questions