我无法弄清楚如何修复我为代码而不断修复的错误
import java.util.Scanner;
public class Unit02Prog1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
System.out.print("name");
name = input.next();
String catagory;
System.out.print("Catagory");
catagory = input.next();
String numWords;
System.out.print("numWords");
numWords = input.next();
int price;
if (numWords >= 50) {
price = ((numWords -50) * .08) + 5.00;
System.out.println("customer:" + name);
System.out.println("Placed an ad in catagory:" + catagory);
System.out.println("Ad length is" + numWords + "words, at a price of $" + price);
}
else {
price = numWords * .10;
System.out.println("customer:" + name);
System.out.println("Placed an ad in catagory:" + catagory);
System.out.println("Ad length is" + numWords + "words, at a price of $" + price);
}
}
}
这些是获得相同错误但在结尾处具有不同符号的行
if (numWords >= 50) {
二元运算符'<='的坏操作数类型
price = ((numWords -50) * .08) + 5.00;
二元运算符的坏操作数类型' - '
price = numWords * .10;
二元运算符'*'的坏操作数类型
我该如何解决这些问题
4 回答
你的变量
numWords
是字符串,请先将其解析为整数进行比较 . 然后,将price
更新为双倍 . 示例代码如下 .numWords
是String
,而不是int
. 解析String以获取int .你做错了什么
numWords是一个字符串,
>=
仅适用于数字 .如何修复
你有2个选项来解决这个问题:
这种方式意味着您可以手动检查,如果数字错误则不需要捕获异常 .
这种方式代码较少,但如果输入不是整数,则需要捕获
NumberFormatException
.其他说明
您经常使用
input.next()
,具体取决于您的输入,您可能需要使用nextLine
您可能需要使用
System.out.printf
来清理打印代码在这种情况下,您需要从字符串解析为整数 . 这里有一个例子:
在你的代码中:
public static void main(String [] args){Scanner input = new Scanner(System.in);