Java比较文件与控制台输入
我的代码有问题,我不知道为什么不进行比较,但打印得很好。这是我的密码Java比较文件与控制台输入,java,Java,我的代码有问题,我不知道为什么不进行比较,但打印得很好。这是我的密码 public void read() throws IOException { String entered = one.next(); // Read from the console try (BufferedReader reader = new BufferedReader(new FileReader("file.csv"))) { while (true)
public void read() throws IOException {
String entered = one.next(); // Read from the console
try (BufferedReader reader = new BufferedReader(new FileReader("file.csv"))) {
while (true) {
String line = reader.readLine(); // Read file line
if (line == null) {
break;
} //Break if there is no more lines
String[] lineTwo = line.split(","); // Split into Array the line to compare it
if (lineTwo[1].replaceAll(" ", "") == entered.replaceAll(" ", "")) {
// compare record 1 with the entered value replace all is not needed I was testing if it have some spaces
System.out.println("entered");
}
System.out.println(lineTwo[0]);
}
}
}
它打印文件的所有信息,但是当我要比较它时,条件永远不会被打印出来。首先从控制台读取,然后读取文件行。。如果记录[1]=是从控制台输入的,则行并进行比较。出于某种原因,打印全部,但不输入if语句。您的代码:
lineTwo[1].replaceAll(" ", "") == entered.replaceAll(" ", "")
应该是:
lineTwo[1].replaceAll(" ", "").equals(entered.replaceAll(" ", ""))
在
Java
中,需要知道何时要比较String
,需要使用equals
方法。因为=
将比较字符串
对象的引用
。因此,如果您比较两个字符串
对象,则引用
不相同。您编写了什么代码进行比较?停止使用=
与字符串
!使用string方法equals比较字符串,而不是==该方法比较cvs文件上的记录以允许注册用户Oh Omg感谢我不知道此错误==:)现在工作正常