0

i want to ask a question for a bedsize and while the answer is not what i choose it will be i want that it will ask the user to answer again

import java.util.Scanner;

public static void main(String[] args) {
    String newBedType ;
    Scanner sc1 = new Scanner(System.in) ;
    System.out.println("you want a single bed or doublebed? ") ;
    newBedType = sc1.next() ;

    while (newBedType != "single" + "doublebed") {
    System.out.println("please choose againe the bed size: ");
    newBedType = sc1.next() ;
    switch (newBedType) {
    case "single" : System.out.println("i see you like sleeping alone"); 
    break ;
    case "doublebed" : System.out.println("got company ;) ");
    break ;
    }

    }               

}

}

the code kinda works it shows the cases if i write the correct string but it will continue to ask me forever.....

i just stared learning java so be easy on me i know its a stupid question but after hours of trying and searching here(though i did found in python but dont know how to "translate" it to java) i cant figure it out... thanks to anyone willing to help :)

rollcage
  • 101
  • 1
  • 10

1 Answers1

0

Your issue is with the line:

 while (newBedType != "single" + "doublebed")

This doesn't do what you think it does. You are comparing the variable newBedType with the string "singledoublebed", the addition operator is concatenating those two strings. You want the line:

 while (!newBedType.equals("single") && !newBedType.equals("doublebed"))

Note the use of the .equals() method, as string comparisons in Java do not act as expected with the == or != operators.

Jacob H
  • 864
  • 1
  • 10
  • 25
  • 1
    This would even be unessecary if he labeled the while loop and reused the comparison in the switch to break to that label. – S.Klumpers Apr 10 '16 at 16:28