【问题标题】:Code skips if statement even though parameters are correct即使参数正确,代码也会跳过 if 语句
【发布时间】:2015-04-26 10:32:38
【问题描述】:

此代码应该以这种格式“$(金额)”从客户那里获取输入。 if 语句用于检查字符串 payment 中的第一个字符是否等于“$”,但这不会触发 if 语句,它一直将其读取为无效付款。

double money = 0;
String payment = input.next();
String $ = "$";
String test = payment.substring(0);
if (test.equals($)) {
  System.out.println("You entered " + payment);
  payment = payment.substring(1, payment.length() - 1);
  money = Double.parseDouble(payment);
  if ( money < sum ) {
    System.out.println("Not enough money. System terminating.");
    System.exit(0);
  }
System.out.println(payment);
}
else {
  System.out.println("Invalid coin or note. Try again.");
  payment = input.next();
}

【问题讨论】:

  • 您认为substring(0); 会做什么?如果要抢第一个字符,只需使用if (payment.charAt(0) == '$')...
  • 不建议将变量命名为$
  • 添加到@MarounMaroun,来自java文档chapter 3.8 identifiersThe $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

标签: java string if-statement


【解决方案1】:

payment.substring(0)返回整个String,你想比较"$"payment.substring(0,1),或者比较payment.charAt(0)'$'

所以要么:

String test = payment.substring(0,1);
if (test.equals($)) {

if (payment.charAt(0) == '$') {

会起作用的。

另一种选择是:

if (payment.startsWith ($)) {

【讨论】:

    【解决方案2】:

    不建议子字符串匹配字符。

    if(payment.charAt(0)=='$')
    

    或者使用正则表达式

     Pattern p=Pattern.compile("$.*");
    
     Matcher m=p.matcher(payment);
    
     if (m.matches()==true) {
         /*Do operation*/
     }
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多