0

Does the scanner function nextLine() have a different data type to String?

I am attempting an extremely basic code - basically just asking the user which type of vehicle they choose and returning a message of how many wheels that vehicle has. Since the code hasn't been working, Firstly made the code return exactly what was entered in to make sure what's been entered was processed correctly and secondly, I've entered a while loop that will repeatedly ask for input as long as the input value does not equal to either 'car','Car,'bike' or 'Bike'. This is the code: import java.util.Scanner; public class Simple { public static void Car(){ System.out.println("Car has 4 wheels"); } public static void Bike(){ System.out.println("Bike has two wheels"); } public static void main(String[] args) { boolean loop = true; while (loop = true){ System.out.println("Test 2: Car or Bike?"); Scanner vType = new Scanner(System.in); String Vehicle = vType.nextLine(); System.out.println(Vehicle); if (Vehicle == "Car" || Vehicle == "car"){ System.out.println("I'ts equal to car / Car"); loop = false; Car(); } else { System.out.println("It isn't equal to car / Car"); } if (Vehicle == "Bike" || Vehicle == "bike"){ System.out.println("it is equal to bike / Bike"); loop = false; Bike(); } else { System.out.println("it isn't equal to bike / Bike"); } } } } I would give a potato for the long post if I knew how to code it.

31st Mar 2020, 12:56 PM
Stephen Jeffery
Stephen Jeffery - avatar
4 Réponses
+ 4
In while loop condition use == not = == compares = assigns Use equals() method of String class to check string equality . == will check whether both references are referring to same object. You can also use equalsIgnoreCase() for case insensitive comparison.
31st Mar 2020, 1:12 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 3
while loop condition replace = with ==
31st Mar 2020, 1:09 PM
你知道規則,我也是
你知道規則,我也是 - avatar
31st Mar 2020, 1:36 PM
Avinesh
Avinesh - avatar
0
How could I implement that equalsIgnoreCase() method in the for loop, if I may ask?
31st Mar 2020, 1:19 PM
Stephen Jeffery
Stephen Jeffery - avatar