-2

I'm trying to check if the text file contains "Circle" or "Square" and if so to read the rest of the line. I have tried using scan.next()=="Circle" but that doesn't seem to work. EDIT: The numbers refer to x and y coordinates which will be implemented into an instance of a class. In this case, Square and Circle.

Text File:

Circle 50 60 40 50 50
Square 250 260 45 -50 -50
jacko1445
  • 5
  • 1
  • 5
  • 2
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – GhostCat Apr 17 '15 at 11:37
  • 1
    You should start with learning about the fundamental concepts of Java; for example: instead of worrying about how to read a file ... step back and learn about the proper ways to compare objects in Java. – GhostCat Apr 17 '15 at 11:37

3 Answers3

0

If you are reading from a text file try using a BufferedReader and then using readLine and then using .equals() instead of ==

An example:

BufferedReader reader = new BufferedReader(new FileReader(myTextFile));
String lineOne = reader.readLine();
if(lineOne.equals("circle"))
{
  //do something
}
Nived
  • 1,804
  • 1
  • 15
  • 29
0

In Java, the “==” operator is used to compare 2 objects. It checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. So you should make use of equals. But in your case, if a line starts with circle or square you have to read the line from the given file.

Can you use the following condition and check if it works with scanner itself?

    String line = sc.next();
    if (line.startsWith("Circle") || line.startsWith("Square")){
        //Your logic
    }
Rajesh
  • 382
  • 3
  • 14
0

Try this:

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

public class FileReader {

    public FileReader() {
        Scanner scanner;
        List<String> list;
        try {
            list = new ArrayList<>();
            scanner = new Scanner(new File("file.txt"));
            while (scanner.hasNextLine()) {
                String s = scanner.nextLine();
                if (!s.startsWith("Circle") && !s.startsWith("Square")) {
                    break;
                }
                System.out.println(s);
                list.add(s);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new FileReader();

    }

The file is called file.txt:

Circle 50 60 40 50 50
Square 250 260 45 -50 -50
False 50 60 40 50 50

If you compare Strings, always use equals not ==. Check this out

Klemens Morbe
  • 595
  • 9
  • 24