简体   繁体   中英

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ':'

I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.

import java.util.Scanner;
public class MyClass {  
public static void main(String args[]) {
    Scanner stats = new Scanner(System.in);      
     double base,current;
     float bonus;
     int level;
     
     System.out.print("Enter the base attack speed: ");
     base = stats.nextDouble();
     
     System.out.printf("Enter the bonus attack speed %: " + "%.2f");
     bonus = stats.nextFloat();
     
     System.out.println("Enter the level: ");
     level = stats.nextInt();
     
     current = (base*1+bonus*level-1) /100;
     System.out.print("The character's current speed is: " + current);
     
   }
}

% is what printf (and String.format ) use for identifying a placeholder which will be filled in by a parameter provided as second argument.

You therefore have 2 bugs in this code:

  1. The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: " .

  2. You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue); . If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90" , because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.

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