我想從使用Java的Character數組中返回用戶輸入子串的索引。該數組被初始化,加擾,然後被搜索。我是新手,嘗試了兩種不同的方法,但都沒有成功。我忽略了什麼?提前致謝。使用Java在數組中找到子串索引
方法1:
import java.lang.Math;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class ArrayRandomChar {
public static void main(String[] args) {
// Create an array of characters:
Character[] anArray = {'P', 'A', 'P', 'A', 'B', 'E', 'A', 'R'};
for (char ch: anArray)
System.out.print(ch + " ");
System.out.println();
// Create list from array and shuffle
List<Character> aList = Arrays.asList(anArray);
Collections.shuffle(aList);
System.out.print(aList);
System.out.println();
// Bring back into array
Object ob[] = aList.toArray();
for (Object ch: anArray)
System.out.print((Character) ch + " ");
// User input
Scanner input = new Scanner(System.in);
String letter = input.next();
System.out.println(letter);
// Return index of letter, -1 if doesn't contain
int retval = aList.IndexOf(letter);
System.out.println(retval);
}
}
問題:運行文件,輸入字母時,-1返回即使列表包含字母。
方法2:
public class ArrayRandomChar {
public static void main(String[] args) {
// Create an array of characters:
Character[] anArray = {'P', 'A', 'P', 'A', 'B', 'E', 'A', 'R'};
for (char ch: anArray)
System.out.print(ch + " ");
System.out.println();
// Create list from array:
List<Character> aList = Arrays.asList(anArray);
Collections.shuffle(aList);
System.out.print(aList);
System.out.println();
//create array from list
Object ob[] = aList.toArray();
for (Object ch: anArray)
System.out.print((Character) ch + " ");
//user input
Scanner input = new Scanner(System.in);
String letter = input.next();
int index = Arrays.binarySearch(anArray, letter);
System.out.println(~index);
System.out.println(letter);
}
}
這引發異常:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Character
at java.lang.Character.compareTo(Character.java:101)
at java.util.Arrays.binarySearch0(Arrays.java:2001)
at java.util.Arrays.binarySearch(Arrays.java:1943)
at ArrayRandomChar.main(ArrayRandomChar.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
難道你不明白什麼錯誤消息? –
以'at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)'開頭的所有內容' 我想知道這是否可以通過兼容Character的掃描器input.next()來解決。 – user25976