【发布时间】:2016-04-19 18:11:26
【问题描述】:
只是希望获得一些关于代码的指导。对于第一位(见下文),我正在尝试创建一个几乎可以添加给定值的实例方法。我的问题是我不断收到非法的表达式开始错误。我想知道是否有人能够解释为什么,因为它对我来说看起来不错?请记住,我只发布了我收到错误消息的代码部分。
编辑我实际上想重新打开这个问题一秒钟,因为无论出于何种原因,我都收到了一个奇怪的错误。我能够完成代码,但是当我测试它时收到一条错误消息,说明 IllegalArgumentException:所选字母无效。必须是 T、D 或 E。给定的数据 84 将被忽略。我想知道为什么会出现错误消息,因为我选择了这些字母并且我根本没有使用 84 作为数字。
public int addNewValue ( char amtType, int amount) {
Scanner keyboard= new Scanner (System.in);
System.out.println("Please enter the amount in dollars");
amount=keyboard.nextInt();
System.out.println("Please select the amount Type: T-Ticket Sales,"
+ " D-Donations, E-Expenses");
amtType=keyboard.next().charAt(0);
if (amount<=0) {
throw new IllegalArgumentException("Amount must be positive and "
+ "non-zero. The given data " +amount+ " will be ignored.");
//below is where I recieve the error message
}else if (amtType !=T&&!=D&&!=E ) {
throw new IllegalArgumentException ("The letter chosen is invalid."
+ "Must be T, D, or E. The given data " +amtType+
" will be ignored");
}else{
return amount + amtType;
}
}
【问题讨论】:
-
amtType !=T|!=D|!=E是什么? -
可能你想要
if ( (amtType!='T') && (amtType!='D') && (amtType!='E') ) -
@Lashane 你好!本质上,我希望用户只使用字母 T、D 或 E,因为这些字母在代码的其他地方有一个设定值。如果他们没有选择,我希望出现一条错误消息。我是java新手,所以据我了解!= 与不等于正确吗?还是没有在那种情况下使用?
-
你是对的,
!=是不等于运算符。但是a != b | != c是无效的语法。您不能像这样链接运算符,而是必须使用由&&(和)运算符分隔的两个测试,就像a != b && a != c一样,就像@Lashane 说的那样。请注意,您需要 and 运算符,而不是 or 运算符。 -
啊,好吧,这更有意义。非常感谢!
标签: java runtime-error performance-testing