【问题标题】:charAt not working in java fraction calculatorcharAt 在 java 分数计算器中不起作用
【发布时间】:2017-11-29 20:34:29
【问题描述】:

即使输入有下划线,此代码也会返回 false。 输入类似于 1_3/4 + 3 并返回 4_3/4

  String[] Separated = fraction.split(" "); //Splits the tokens up
  String firstToken = Separated[0]; // I created this to try to troubleshoot
  boolean Mixed = true; //This would determine how much I will need to split up
  for(int i = 0; i < firstToken.length(); i++) {
     if(firstToken.charAt(i) == '_') { 
        Mixed = true;
     }
     else {
        Mixed = false;
     }
  }

【问题讨论】:

  • charAt 工作得很好。另一方面,是什么阻止了 Mixed 被设置回 false?
  • 哦,对了,我很糟糕,谢谢。

标签: java if-statement charat


【解决方案1】:

您可以使用“包含”来代替 for 循环:

boolean mixed = firstToken.contains("_");

请在 java 中使用小写的变量名。

【讨论】:

    【解决方案2】:

    如果您想获得下划线字符的位置,可以快速修复我们的代码:

    String firstToken = "_"; // I created this to try to troubleshoot
        boolean Mixed = true; //This would determine how much I will need to split up
        int i;
        for(i = 0; i < firstToken.length(); i++) {
            if(firstToken.charAt(i) == '_') {
                Mixed = true;
                break;
            }
            else {
                Mixed = false;
            }
        }
        //i gives the index of underscore
    

    虽然有更简洁的方法可以做到这一点。 这应该得到下划线的索引

        String firstToken = Seperated[0]; // I created this to try to troubleshoot     
        int index==firstToken.indexOf('_');
    

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      相关资源
      最近更新 更多