【发布时间】:2021-12-18 23:34:20
【问题描述】:
几天前我必须完成我的学校作业,我想出了这个简单的程序,它根据用户输入的内容返回 true 或 false 值.如果单词以字符 'a' 或 'e' 结尾,程序应该返回 true 值,否则返回 false.. 我们严格需要使用循环和 NOT USE endsWith 或任何其他类来创建我们自己的方法。所以我的想法基本上是将单词拆分为字符并用它们填充一个表,然后最后我使用 if 语句检查保存在表索引中的字符是否匹配 'a ' 或 'e'。我对其他解决方案不感兴趣,我只想解释为什么程序总是返回下面列出的错误。
附言我不是任何编程语言的高级程序员,所以不要评判我。
错误:
java.lang.ArrayIndexOutOfBoundsException: 0
at Homework.myMethod(Homework.java:34)
at Homework.main(Homework.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)enter code here
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
计划:
import java.io.*;
public class Homework
{
public static void main(String[] args) throws IOException
{
//Defined reader
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Instruction for user
System.out.println("Please enter any word you like:");
//Reading user input
String a = in.readLine();
//Showing user output
if(myMethod(a) == true){
System.out.println("Word has char 'a' or 'e' at the end of the word.");
}
else{
System.out.println("Word doesn't have char 'a' or 'e' at the end of the word.");
}
}
//My defined method
public static boolean myMethod(String str)
{
//Empty table
char table[]={};
//Loop
for(int i = 0; i < str.length(); i++)
{
//Grabs first char of word and adds it to the table
table[i] = str.charAt(i);
}
//Check statement to see if there is actually char 'a' or 'e' at the end of the word.
if(table[table.length-1] == 'a' || table[table.length-1] == 'e')
{
return true;
}
return false;
}
}
【问题讨论】:
-
char table[]={};您声明了一个大小为零的数组。代码绝对不正确:)。数组大小不会因为你添加东西而改变。请改用ArrayList。
标签: java arrays sorting indexing