我的程序为我提供java.lang.ArrayIndexOutOfBoundsException:1
我正在编写一个程序,将一个短语翻译成pig拉丁语,方法是创建一个数组,数组中填充用户输入的字符串中的各个单词,然后遍历每个单词,将其转换为pig拉丁语,并将其打印到控制台。在我的方法的while循环中,通常会出现上述错误:我的程序为我提供java.lang.ArrayIndexOutOfBoundsException:1,java,Java,我正在编写一个程序,将一个短语翻译成pig拉丁语,方法是创建一个数组,数组中填充用户输入的字符串中的各个单词,然后遍历每个单词,将其转换为pig拉丁语,并将其打印到控制台。在我的方法的while循环中,通常会出现上述错误: package UpGAMING; public class Methods { public void Translator(String s, String[] index, int location) { while (index[loca
package UpGAMING;
public class Methods {
public void Translator(String s, String[] index, int location) {
while (index[location].length() > 0) {
location++;
if(index.length > 0)s = s + index[location].substring(1) + index[location].substring(0,1).toLowerCase() + "ay";
System.out.println(s);
}
}
}
如果我将条件更改为simply whiletrue,我将在此行中得到java.lang.ArrayIndexOutOfBounds:2的错误:
if(index.length > 0)s = s + index[location].substring(1) + index[location].substring(0,1).toLowerCase() + "ay";
下面是我的类,其中包含main方法:
导入java.util.Scanner
公共课基础{
public static void main(String[] args) {
Methods method = new Methods();
Scanner keyboard = new Scanner(System.in);
String input;
int indexer = 1;
String ss = "";
System.out.println("Enter the word or phrase you want to translate to Pig Latin:");
input = keyboard.next();
String[] output = input.split("\\s+");
method.Translator(input, output, indexer);
System.out.println();
}
}
请提供我的代码应该是什么样子的代码块,因为我不是一个有经验的程序员。试试这个,也许你会明白你的代码有什么问题
public class Methods {
public void Translator(String s, String[] index, int location) {
System.out.println("Index Length: " + index.length);
System.out.println("Location: " + location);
if (location >= index.length)
System.out.println("Uppss.. ArrayIndexOutOfBoundException :((( ");
while (index[location].length() > 0) {
location++;
if(index.length > 0) {
s = s + index[location].substring(1)
+ index[location].substring(0,1).toLowerCase()
+ "ay";
}
System.out.println(s);
}
}
}
试试这个
public void Translator(String s, String l, String[] index)
{
for (String word : index) {
String s1=s, l1=l;
if (word.length()> 0) {
s1 = l1 + word.substring(1) + word.substring(0, 1).toLowerCase() + "ay";
l1 = s1;
}
System.out.println(s1);
}
}
大体上,您使用Scanner.next读取输入,然后在空白处将其拆分。但是默认情况下,Scanner已经在空白处进行拆分,并且next只在输入时为您提供下一个单词。因此,我将使用循环中的next读取输入,直到您遇到约定的终止符,例如单词END。或者,您可以使用nextLine而不是next然后像你一样分开
然后在Translator中处理数组。我会采取诸如location
public void Translator(String s, String l, String[] index)
{
for (String word : index) {
String s1=s, l1=l;
if (word.length()> 0) {
s1 = l1 + word.substring(1) + word.substring(0, 1).toLowerCase() + "ay";
l1 = s1;
}
System.out.println(s1);
}
}