这是我的customer.csv文件:
1, Ali,1203456789, Normal
2, Siti,134567890, Normal
3, Bob,1568980765, Normal
我想将我输入的名称的Normal状态更改为Cased,但我的代码似乎有问题。这是我的代码:
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the customer you want to flag as Cased:");
String flagCus = input.nextLine();
ArrayList<String> customersFlagged = new ArrayList<String>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] items = lines.get(i).split(",");
if (items[1] == flagCus){
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + "Cased";
customersFlagged.add(enterList);
} else{
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + items[3];
customersFlagged.add(enterList);
}
}
我认为问题是如果(items[1]==flagCus(一行,但我不确定哪里出了问题,我一直在尝试添加一个"在我的flagCus之前执行if语句,但它仍然出错。有人能帮我检查一下这个代码吗?感谢您的关注。
编辑:我应该把代码(items[1]=flagCus(改为(items[1]。等于("+flagCus(。谢谢大家的帮助。
当比较两个对象而不是基元类型时,请使用.equals()
而不是==
。因此:
items[1].equals(flagCus);
若要检查相等的字符串,请改用"string".equals("other")
。
文件中的字符串在开头有一个空格(在逗号上拆分(。
1, Ali,1203456789, Normal
从输入数据中删除这些或调用:
if (items[1].trim().equals(flagCus)){
(正如其他人在回答中指出的那样,使用.equals
来比较String
对象。
完整代码:
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the customer you want to flag as Cased:");
String flagCus = input.nextLine();
ArrayList<String> customersFlagged = new ArrayList<String>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] items = lines.get(i).split(",");
if (items[1].trim().equals(flagCus)){
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + "Cased";
customersFlagged.add(enterList);
} else{
String enterList = items[0] + "," + items[1] + "," + items[2] + "," + items[3];
customersFlagged.add(enterList);
}
}