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.

3/31/2020 12:56:53 PM

Stephen Jeffery

4 Answers

New Answer

+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.

+3

while loop condition replace = with ==

+1

This is how you can use it. https://code.sololearn.com/cqVJ19klDdS5/?ref=app

0

How could I implement that equalsIgnoreCase() method in the for loop, if I may ask?