[英]simple reading from text file
我正在嘗試從文本文件中讀取一些輸入,並且似乎得到一些奇怪的結果。 我有一個文本文件(我確保沒有多余的空格):
acdec
我以字符串形式讀取文本文件,然后將其轉換為數組。 然后,我比較兩個數組中具有相等值的第一個元素,並應執行if語句,但將執行else語句。 這是代碼:
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new FileReader("tester.txt"));
String one = sc.next();
String a[] = one.split("");
String[] b = { "a", "c", "d", "e", "c" };
if (a[0] == b[0]) {
System.out.println("Same");
} else {
System.out.println("Not Same");
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
字符串比較的不同之處在於,必須使用以下內容:
if (a[0].equals(b[0]) {
....
}
當使用==
,您正在比較值所指向的引用 ,而.equals()
在比較實際值 。
也許您需要處理字符數組而不是字符串數組才能獲得測試結果。 請注意,字符用單引號而不是雙引號表示。
public class test {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new FileReader("/Users/908752/tester.txt"));
String one = sc.next();
char a[] = one.toCharArray();
char[] b = { 'a', 'c', 'd', 'e', 'c' };
if (a[0] == b[0]) {
System.out.println("Same");
} else {
System.out.println("Not Same");
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.