字符串索引超出范围解决方案? (Java)的

时间:2017-05-22 20:33:36

标签: java

运行此代码时出错。错误是 线程" main"中的例外情况java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-16。 我不确定如何修复,我已经尝试了多种解决方案。

import java.util.Scanner;
public class Card {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your card: ");
        String number = input.next();

        if(addingDigit(number) % 10 == 0)
            System.out.println("Card is valid");
        else
            System.out.println("Card is invalid");


    }
    public static long addingDigit(String number){

        long even = 0;

        for(int i = 0, s = 2; i < number.length() - 1; i++, s *= 2){
            if(number.charAt(number.length() - s) >= '5'){
                if(number.charAt(number.length() - s) == '5')
                    even += 1;
                else if (number.charAt(number.length() - s) == '6')
                    even += 3;
                else if(number.charAt(number.length() - s) == '7')
                    even += 5;
                else if(number.charAt(number.length() - s) == '8')
                    even += 7;
                else if(number.charAt(number.length() - s) == '9')
                    even += 9;
            }

            else
                even += (number.charAt(number.length() - s) - 48);


        }

        long k = addOdd(number);
        long sumOfDigits = even + k;
        return sumOfDigits;


    }
    public static long addOdd(String number){
        long odd = 0;
        for (int i = 0, s = 1; i < number.length() - 1; i++, s += 2){
            odd += number.charAt(number.length() - s) - 48;

        }
        return odd;

    }
}

2 个答案:

答案 0 :(得分:0)

在尝试访问元素之前,检查number.length() - s是否在范围内。

答案 1 :(得分:0)

你的循环正在增加s的价值而没有限制。因此,在s的某个循环值将大于字符串number的大小之后。这就是你得到错误的原因。这是一种不好的做法。