0

I am trying to create some code that reads a textfile, splits up the text file into smaller chunks, and performs actions depending on what some of the chunks equal to. Here is my example text file.

Derek 19 12
Jake 17 1
God 5000 13

The issue that I am running into is that my if-else statements are being completely ignored and only the else statement at the end is being called upon. I would appreciate it if someone could help me to understand what i am doing wrong. Here is my code(The text file and the code shown are simplified versions of a much larger program that i am working on. I have tested the code to make sure that the error is still there). Any help that anyone could provide would be greatly appreciated.

package testProgram;

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

public class IfElseStatmentTest {

public static void main(String[] args) {
    String fileName = "NumberData.txt";
    Scanner inputStream = ReadInputFile(fileName);
    while (inputStream.hasNextLine()){
        String newLine = inputStream.nextLine();
        String[] data = newLine.split(" ");
        if (data[0] == "Derek")
            System.out.println("Hi Derek");
        else if (data[0] == "Jake")
            System.out.println("Hi Jake");
        else if (data[0] == "God")
            System.out.println("Hi God");
        else
            System.out.println("kaboom");
    }

}

public static Scanner ReadInputFile(String fileName){

    Scanner inputStream = null;

   try {
       inputStream = new Scanner(new File(fileName));
       return inputStream;
   }
   //display an error message if you have trouble opening the file             
   catch(FileNotFoundException e) {
       System.out.println("Error opening the file " + 
                           fileName);

       System.exit(0);
       return inputStream;
   }

    }

}

Here is the incorrect output that I am getting

kaboom
kaboom
kaboom

Here is the output that i am supposed to be getting.

Hi Derek
Hi Jake
Hi God
Tom
  • 47
  • 8

0 Answers0