-2

i have a little problem with my code,

import java.util.Scanner; 
public class Exercice8BIS {

    int indexString(String needle, String [] search) {
        int index = -1;
        for (int i = 0; i < search.length; i++ ) {
            if ( needle == search[i] ) {
                index = i;
                break;
            }
        }
        return index;
    }

    public Exercice8BIS() {
        Scanner saisieUtilisateur = new Scanner(System.in);
        System.out.println("Veuillez saisir le nom d'un mois (en miniuscule et sans accent) pour obtenir son nombre de jour :");
        String nomMois = saisieUtilisateur.next();
        saisieUtilisateur.close();
        System.out.print(nomMois);
         
        String [] mois = {"janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre"};
        
        int [] jourParMois = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        int nombreJour = jourParMois[ indexString(nomMois, mois) ];
        System.out.println("Le nombre de jour du mois de " + nomMois + " est de " + nombreJour + ".");
    }

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

So when I ask the variable nomMois from the user with the library scanner and after I use the function indexString, I test the conditions nomMois == mois[I] with needle == search[I] in indexString, it's every time false even if I put janvier for nomMois. I don't understand why it's false and I don't have idea to correct it, can you help me ?

Quxntin
  • 39
  • 5

1 Answers1

-1

Strings (and objects) need to be compared using .equals() unless you are checking specifically if you have the same reference to the object.

if ( needle.equals(search[i]) ) {
TheNytangel
  • 431
  • 1
  • 6
  • 15