简体   繁体   English

重复Java数组

[英]Repeating Java Array

I'm new to java and still learning, so keep that in mind. 我是Java的新手,仍然在学习,因此请记住这一点。 I'm trying to write a program where a user can type in a keyword and it'll convert it to numbers and put it in an array. 我正在尝试编写一个程序,用户可以在其中键入关键字,并将其转换为数字并将其放入数组中。 My problem is the array needs to keep repeating the int's. 我的问题是数组需要继续重复int。

My code is: 我的代码是:

String keyword=inputdata.nextLine();
int[] key = new int[keyword.length()];
for (int k = 0; k < keyword.length(); ++k)
{
    if (keyword.charAt(k) >= 'a' && keyword.charAt(k) <= 'z')
    {
        key[k]= (int)keyword.charAt(k) - (int)'a';
    }
}

Right now if I try to get any key[i] higher than the keyword.length it throws an outofbounds error. 现在,如果我尝试将任何key[i]高于keyword.length则会引发出outofbounds错误。 I need it to to be infinte. 我需要它是无限的。

So basically, if keyword.length() were 3 I need to be able to see if key[2] is the same as key[5] and key[8] and so on. 因此,基本上,如果keyword.length()为3,我需要能够看到key[2]是否与key[5]key[8] ,依此类推。

Thanks for your help! 谢谢你的帮助!

Well, it's easiest to fix your code with a bit of refactoring first. 好吧,最简单的方法是先重构一下,然后再修复代码。 Extract all uses of keyword.charAt(k) to a local variable: keyword.charAt(k)所有用法提取到局部变量中:

for (int k = 0; k < keyword.length(); ++k)
{
    char c = keyword.charAt(k);
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c'a';
    }
}

Then we can fix the issue with the % operator: 然后,我们可以使用%运算符解决此问题:

// I assume you actually want a different upper bound?
for (int k = 0; k < keyword.length(); ++k)
{
    char c = keyword.charAt(k % keyword.length());
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c - 'a';
    }
}

That's assuming you actually make key longer than keyword - and you probably want to change the upper bound of the loop too. 假设您实际上使key长度大于keyword长度-并且您可能还想更改循环的上限。 For example: 例如:

int[] key = new int[1000]; // Or whatever
for (int k = 0; k < key.length; ++k)
{
    char c = keyword.charAt(k % keyword.length());
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c - 'a';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM