字符串索引超出范围(重复数字序列)

时间:2014-12-03 13:27:59

标签: java arrays

我的代码似乎遇到问题,即查找重复的数字序列。我已将(?)double转换为字符串,因为我得到了错误无法访问的语句。 (我猜这有助于找出我现在收到错误的原因吗?)。

每当我运行它,它就会很好,直到我完成进入N和D.

它会说“线程中的异常”主“java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:3”

以下是我的代码:

import java.util.*; 
public class RepeatingSequence{
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter N,D: ");
    int numerator = in.nextInt();
    int denominator = in.nextInt();

    double quotient = numerator / denominator;
    String number = "" + quotient;
    char n = number.charAt(0);
    int j = 1;
    int z = 0;
    String output = "";
    char[] index = number.toCharArray();

    for ( int i = 2; number.charAt(j) != number.charAt(i); i++ ){
        index[z] = number.charAt(z);
        index[j] = number.charAt(j);
        index[i] = number.charAt(i);
        output = output + index[i];

        if ( index[i] != index[z] ){
        System.out.print(index[z] + ".(" + index[j] + output + ")");
        }
    }   
}
}

3 个答案:

答案 0 :(得分:1)

只需添加i< number.length()到条件

( int i = 2; i < number.length() && number.charAt(j) != number.charAt(i); i++ )

答案 1 :(得分:0)

对于您的例外情况,我认为您应该编写更安全的代码 - 这些内容符合以下内容:

int len = number.length();

for ( int i = 2; (i < len) && (j < len) && 
          number.charAt(j) != number.charAt(i); i++ ){
 ... 
} 

我并非试图解决您要解决的问题,而只是解决您所面临的问题。对不起。

答案 2 :(得分:0)

我改变了你的代码,试一试,看看你的想法:

public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter N,D: ");
    double numerator = in.nextDouble();
    double denominator = in.nextDouble();

    double quotient = numerator / denominator;
    String number = "" + quotient;
    char n = number.charAt(0);
    int j = 1;
    int z = 0;
    String output = "";
    char[] index = number.toCharArray();
    int max = -1;
    int currentNumber = -1;
    int temp = -1;
    int tempMax = -1;
    System.out.println("" + quotient);
    boolean check = true;
    for(int i = (number.indexOf(".") + 1); i < index.length; i++)
    {
        if(max == -1)
        {
            currentNumber = i;
            temp = i;
            max = 1;
            tempMax = 1;
        }
        else
        {
            if(index[i] == index[i-1])
            {
                tempMax++;
            }
            else
            {
                if(tempMax > max)
                {
                    check = false;
                    max = tempMax;
                    currentNumber = temp;
                }
                tempMax = 1;
                temp = i;
            }
        }
    }
    if(check)
    {
        max = tempMax;
    }
    System.out.println(index[currentNumber] + " repeats " + max + " times.");
}

输入/输出示例:

Enter N,D: 1
3
0.3333333333333333
3 repeats 16 times.