我目前正在为即将到来的一次实践考试做练习题,但被卡住了.我已经编写了一种方法来判断一组三张牌是否有效或无效,其中我们被告知"如果两张牌的形状、 colored颜色 或图案不同,即它们的属性都不匹配,则两张牌是不同的.如果两张牌的形状、 colored颜色 和图案相同,即它们的所有属性都匹配.如果一组三张牌由(I)三张不同的牌,或(Ii)三张相同的牌组成,则三张牌是有效的."目前,如果我运行我的程序,每组三张卡都被判断为"有效".我非常确定问题不在于我读入和存储卡片及其属性的方式,因为我已经对其进行了调试,所以我假设问题出在我的卡片AreValid方法的逻辑上,特别是我如何比较每个卡片的不同字符串元素(属性).然而,我可能错了.请帮帮忙.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Check {
public static boolean cardsAreValid(String [][] threeCards){
boolean sameShape = threeCards[0][0].equals(threeCards[1][0]) && threeCards[1][0].equals(threeCards[2][0]);
boolean sameColour = threeCards[0][1].equals(threeCards[1][1]) && threeCards[1][1].equals(threeCards[2][1]);
boolean samePattern = threeCards[0][2].equals(threeCards[1][2]) && threeCards[1][2].equals(threeCards[2][2]);
if (sameShape == true && sameColour==true && samePattern==true) // if all attributes match - same so valid
return true;
else if (sameShape==false && sameColour==false && samePattern==false) // if no attributes match - distinct so valid
return true;
else
return false; // if only 1 or 2 cards differ/match its invalid
}
public static void main (String [] args) {
File inFile = new File("cards.txt");
String [][] cards = new String[3][3];
List<String> allLines = new ArrayList<>();
try (Scanner sc = new Scanner(inFile)) {
while (sc.hasNextLine()) {
allLines.add(sc.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < allLines.size(); i++) {
String fullLine = allLines.get(i);
System.out.println("Processing: " + fullLine);
String [] singleCard = fullLine.split(" ");
for (int j = 0; j < 3; j++) {
int firstComma = singleCard[j].indexOf(",", 0);
int secondComma = singleCard[j].indexOf(",", firstComma+1);
String shape = singleCard[j].substring(0, firstComma);
String colour = singleCard[j].substring(firstComma+1, secondComma);
String pattern = singleCard[j].substring(secondComma+1);
cards[j][0] = shape;
cards[j][1] = colour;
cards[j][2] = pattern;
}
if (cardsAreValid(cards) == true) {
System.out.println("Valid");
}
else
System.out.println("Invalid");
}
}
}
以防万一,示例文本文件cards.txt如下所示:
square,blue,spot circle,red,solid triangle,green,stripe
square,blue,spot circle,red,solid triangle,green,solid
square,blue,spot square,blue,spot square,blue,spot square,blue,spot
square,blue,spot triangle,green,stripe