幾天前我不得不完成我的學校作業,我想出了這個簡單的程式,它根據用戶輸入的內容回傳真值或假值。如果單詞以字符 ' a ' 或 ' e '結尾,程式應該回傳真值,否則回傳假.. 我們嚴格需要使用回圈創建我們自己的方法,而不是使用endsWith 或任何其他類。所以我的想法基本上是將單詞拆分為字符并用它們填充一個表,然后在最后我使用if陳述句來檢查保存在表索引中的字符是否匹配 ' a ' 或 ' e'。我對其他解決方案不感興趣,我只想解釋為什么程式總是回傳下面列出的錯誤。
PS 我不是任何編程語言的高級程式員,所以不要評判我。
錯誤:
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;
}
}
uj5u.com熱心網友回復:
問題是char table[] = {}這是一個空陣列,那么你不能在其中賦值,你可能需要用一個大小來創建它
char[] table = new char[str.length()];
有一個更好的方法是str.toCharArray(). 此外,當您true/false根據條件回傳時,只需回傳條件
public static boolean myMethod(String str) {
char[] table = str.toCharArray();
return table[table.length - 1] == 'a' || table[table.length - 1] == 'e';
}
也Scanner更容易使用,并且if (myMethod(a))作為條件就足夠了
Scanner in = new Scanner(System.in);
System.out.println("Please enter any word you like:");
String a = in.nextLine();
if (myMethod(a)) {
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.");
}
uj5u.com熱心網友回復:
陣列具有固定大小。您的陣列的長度基本上是 0。嘗試類似
char table[]= new char[str.length()];
uj5u.com熱心網友回復:
如果您必須使用for回圈,您可以使用它,它本質上(現在我看來)與 azro 的方法相同,只是該toCharArray()方法被顯式地寫為回圈......
if (str == null || str.length() < 1) return false;
char[] chars = new char[str.length()];
for (int i = 0; i < chars.length; i ) chars[i] = str.charAt(i);
return (chars[chars.length - 1] == 'a' || chars[chars.length - 1] == 'e');
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350297.html
