简体   繁体   中英

I'm trying to compare a string but when I have the user input a string it doesn't let them

    System.out.println( "Great! Now select the type of measurement this is so we can convert!");
    System.out.println( "G = Gallons" );
    System.out.println( "I = Inches" );
    System.out.println( "P = Pound" );
    System.out.println( "M = Mile" );
    String userType = input.nextLine();

I enter a number, and then when I should be entering the measurement type (as shown above) it automatically skips to the if statement that is after this. Nothing I've tried has worked. Can anyone help?

You must

input.nextLine();

after your read in number part when you go from reading in a number from scanner to a string

I hope this works and helps you in the future.

Use BufferedReader Class

Try the following code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println( "Great! Now select the type of measurement this is so we can convert!");
  System.out.println( "G = Gallons" );
  System.out.println( "I = Inches" );
  System.out.println( "P = Pound" );
  System.out.println( "M = Mile" );
  String userType = br.readLine();

Import required is:

import java.io.*;

You can campare two string by using String functions

Example:

if(String1.equals(String2)){
//Both the strings are equal
}
else{ 
//Both string are not equal
}

You can even use "campareTo" function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM