lundi 1 janvier 2018

How to properly use a scanner input as a method argument in Java?

When I try the code below it does not work, but if i explicitly put the string itself instead of a variable from the scanner it works.

Example I'm trying to fix:

import java.util.Scanner; 

public class TestFunc {
  public static void main(String [] args) {
    Scanner keyboard = new Scanner(System.in); 
    String inputz = keyboard.nextLine();
    System.out.println(testMethod(inputz));
    keyboard.close();
  }

  public static String testMethod(String input){
   if(input == "a")
      return "No!";
    else if(input == "b") 
      return "Yes!";
    else 
      return "I do not know";
  }
}

Example that works:

public class TestFunc {
 public static void main(String [] args) {
    System.out.println(testMethod("a"));
  }

 public static String testMethod(String input){
    if(input == "a")
      return "No!";
    else if(input == "b") 
      return "Yes!";
    else 
      return "I do not know";
  }
}

Aucun commentaire:

Enregistrer un commentaire