-2

I'm trying to write a simple bit of code to get a input via BufferedReader and then execute some code within another method.

import java.io.*; 

public class main {
    public main() {

    }
    public static String input() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String out;
        try {
            out = br.readLine();
            return out;
        } catch (IOException e) {       
            e.printStackTrace();
            return null;
        }
    }
    public static void someCode() {
        //some code
    }
    public static void main (String[] args) {
        input();
        if(input() == "Input") {
            someCode();
        }
    }
}

Thanks :)

Ryan
  • 61
  • 5
  • 1
    so what's the issue? – Achintha Gunasekara Oct 19 '15 at 02:20
  • 1
    Sorry, but it is **very** unclear just what you're asking -- if you're asking anything, that is. In the future, please ask an actual question with your question. If you see errors, describe them and show all error messages. Don't leave us guessing. – Hovercraft Full Of Eels Oct 19 '15 at 02:21
  • 2
    One problem -- you never create an Input variable. The other, Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Oct 19 '15 at 02:22
  • 1
    Also, take a look at [The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) for some ideas about how to better manager your resources and make they are closed when you are done with them – MadProgrammer Oct 19 '15 at 02:23

2 Answers2

0

Store the function in a variable like this:

String x = input(); 
  if("Input".equals(x)) { 
    //do something
  }

Also notice how I used .equals not == as == compares adresses in memory not the value.

0

You're calling the method once, throwing the result away, and then calling it again; the second time is probably not going to give you the results you want. Save the input in a variable instead:

String input = input();
if(input.equals("Input")) {
    ...
}

(You're also erroneously using == instead of .equals; see the code above.)

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152