我正在制作一个小项目,我陷入了阶段:
我试过if(char []!= charInput)和Arrays.asList(char []。contains(charInput)代码但是它们都不起作用。最终每个char都被添加到数组中。我做错了吗?
下面的代码:
package O01_Arrays;
import java.util.Arrays;
import java.util.Scanner;
public class Array_16_play {
public static void main(String[] args) {
int go = 0;
int repeat = 0;
char[] arr = { 'a', 'b', 'c', 'd' }; // Insert chars
String[] arr2 = { ".", ".", ".", "." }; // Here the chars that are not
// in the above char will be
// included
Scanner in = new Scanner(System.in);
while (repeat < 4) // Repeat thread 4 times
{
System.out.print("enter character: ");
String enterValue = in.nextLine();
char charVal = enterValue.charAt(0); // Transform String to Char
boolean answer = false; // Boolean to check if it finds new chars or
// not
for (int i = 0; i < arr.length; i++) {
if (Arrays.asList(arr[i]).contains(charVal)) {
answer = true;
}
else if (answer = false) {
arr2[go] = enterValue; // Fills with new chars !! DOES NOT
// WORK :( !!!
}
System.out.print(arr2[i]);
}
System.out.println();
go++;
repeat++;
}
}
}
答案 0 :(得分:2)
if (answer = false)
可能是此处的问题 - 您需要使用==
代替=
。
通过执行if (answer = false)
,您实际上将答案设为false。
if (Arrays.asList(arr[i]).contains(charVal)) { //<-- this line evaluates
// to false, so you go
// into the else if check
answer = true;
} else if (answer = false) { // <-- this line sets "answer" to false and returns true
// use if (answer == false) instead
arr2[go] = enterValue;
}
第二个问题:您的for循环逻辑错误
1)我不知道为什么你使用复杂的方式检查2个字符是否相同,但arr[i] == charVal
更容易阅读并且可以正常工作
2)您将添加代码放在与检查代码
相同的for循环中这应该是这样的:
for (int i = 0; i < arr.length; i++) { // check the array arr to
if (arr[i] == charVal) { // if it exists, set answer to true
answer = true;
}
}
// if answer is false then we didn't find it and we can add it.
if (answer == false) {
arr2[go] = enterValue;
}
// check the arr2
for (String c : arr2) {
System.out.print(c);
}
答案 1 :(得分:1)
只需按照Aify上面的正确答案继续,假设你只是检查那个小字符数组并且数组已经排序(它是),那么你可以使用Arrays.binarySearch并删除完全是for循环。 以下是代码while部分的更新版本。希望即使像一些新代码一样有用:)
while (repeat < 4) // Repeat thread 4 times
{
System.out.print("enter character: ");
String enterValue = in.nextLine();
char charVal = enterValue.charAt(0);
boolean answer = false;
// Using binary search method instead of the for loop here
answer = Arrays.binarySearch(arr,charVal) >= 0 ? true : false;
if (answer == false) {
arr2[go] = enterValue;
}
// Print out the stored values
for ( String str : arr2 ) {
System.out.println( str );
}
System.out.println();
go++;
repeat++;
}