-1

The method I'm hoping to execute doesn't acknowledge whenever a "y" is inputed into the scanner. It doesn't execute the first part of the if statement, it immediately skips to the else. I'm not sure why it isn't working, is it because I have several scanners running at once? The goal is to use the for loop to store several answers into an array and then manipulate the array with another method. any help to why would be great!

    private static float[] assignMarkArray = {0,0,0};


    public static void setAssignMark(int index, float value) {
        assignMarkArray[index] = value;
    }

    public static void setLabMark (int index, float value) {
        labMarkArray[index] = value; 
    }

    public static void enterAssignGrades() {
    System.out.println("Do you have any assignment Marks? (y/n)");
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();
    if (input == "y"){
        for(int q = 0; q < 3; q++) {
            System.out.println("Do you have a mark for A" + (q+1) + "(y/n)");
            Scanner sc2 = new Scanner(System.in);
            String input2 = sc2.nextLine();
            if (input2 == "y") {
                System.out.println("Enter your A" + (q+1) + " mark (Out of 100%): " );
                Scanner sc3 = new Scanner(System.in);
                float gradeInput2 = sc3.nextFloat();
                setAssignMark(q, gradeInput2);

            }else if (q==3) {
                sc.close();
                sc2.close();
            }
            else{
                setAssignMark(q, 0);
            }
        }
    }
    else{ System.out.println("There are no assignment grades to mark");
          sc.close();
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
Jay
  • 185
  • 2
  • 7
  • 21

3 Answers3

1

use this for checking String values

if (input.equals("y")){

For Example

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.equals("y")){  /// Test for Value Equivalence
System.out.println("Hello");
} else {
System.out.println("By bye");
}
Vinayak Pingale
  • 1,315
  • 8
  • 19
1

Because == on Strings compares references, not for lexical equality. You could call equals and that will test if the input is precisely "y", but I would use

if (input.toLowerCase().startsWith("y")) {
}

Because that will match "Yes", "YES", "yes", or any other word that startwith "y" ... including just "y".

You could also extract the first character, like so -

if (input.toLowerCase().charAt(0) == 'y') { // this will work as expected.
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

When you compare a Java String using == you are actually comparing the address of the String Reference rather than the data contained in the String. To avoid this, the Java String class provides the .equals() method (or equalsIgnoreCase()).

Use one of those for comparing the actual value of the String.

Sid
  • 7,511
  • 2
  • 28
  • 41