为什么我的子字符串导致程序错误?

时间:2018-12-19 23:55:55

标签: java

当我运行该程序时,出现一个错误,说这是由于“ String.substring(int,int)line:不可用。但是,它输出正确的答案(数字为123,目标为2,最终应该是35)。任何帮助都将非常感谢!

import java.util.Scanner;

public class Math{

    public static void main(String[] args) {


        for (int i=1; i<=5; i++) { 
            System.out.println("Please enter your number:");
            Scanner input = new Scanner(System.in);
            String number= input.nextLine();
            System.out.println("Please enter your target:");
            int target= input.nextInt();
            // input.close();


            String outcome= "0";
            long final = Long.parseLong(outcome);

            for (int h=0; h<=((number.length())-target+1); h++) {
                String result = number.substring(h, (target+h));   
                long output = Long.valueOf(result);                    

                final = final + result;

                    System.out.println(final);
            }         
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您在这里遇到几个问题:

  • finalreserved keyword,并且不能是变量名。您必须重命名

  • 您正在尝试将String添加到行中的long

    final = final + result;

  • 调用substring时出现索引超出范围错误。您需要再循环一次。将<=更改为<

代码:

String outcome= "0";
long finalVar = Long.parseLong(outcome);

for (int h=0; h<((number.length())-target+1); h++) {
     String result = number.substring(h, (target+h));   
     long output = Long.valueOf(result);                    
     finalVar = finalVar + output;

}         
System.out.println(finalVar);

输入/输出:

Please enter your number:
123
Please enter your target:
2
35