Soo我的程序正在工作......但只有一個問題...... null也隨着內容或字符串被打印從文件中...無論如何,我可以阻止null被打印。讀取的代碼要求用戶提供文件名.txt,然後向用戶詢問他/她想要搜索的字符,程序在字符串中搜索指定的字符,打印出文本文件的內容並且告訴它被發現了多少次。問題是打印出文本文件(字符串)的內容後,它也會打印出null字樣,但null不在txt文件中。JAVA;當文件中的字符串被打印在屏幕上時null也被打印在一起
import java.util.Scanner;
import java.io.*;
public class filefinder
{
public static void main(String[] args) throws IOException
{
//needed for scanner class
Scanner kb = new Scanner(System.in);
int charCount = 0;
String filename = "";
String str = "";
String line = "";
boolean isString = false;
boolean fileFound = false;
FileReader freader;
// get users string
while (!fileFound)
{
while (!isString)
{
try { Thread.currentThread().sleep(500); }
catch (Exception e) { }
System.out.println("Please enter a filename: ");
System.out.println("");
filename = kb.nextLine();
if (filename != null)
isString = true;
}//end inner while loop
// open file
try
{
freader = new FileReader(filename);
fileFound = true;
Thread.currentThread().sleep(1500);
}
catch (Exception e)
{
System.out.println("");
System.out.println("The system cannot find the file specified.");
System.out.println("");
isString = false;
}//end try-catch
}//end outer while loop
try { Thread.currentThread().sleep(1000); }
catch (Exception e) { }
freader = new FileReader(filename);
BufferedReader inputFile = new BufferedReader(freader);
// Read first line from file
while (line !=null)
{
line = inputFile.readLine();
if (line != null)
try { Thread.currentThread().sleep(1000); }
catch (Exception e) { }
str = str+ "\n" + line;
}//end while
System.out.println(str);
inputFile.close();
// get users character
System.out.println("");
System.out.println("Please enter a character you want to find: ");
System.out.println("");
char userChar = kb.nextLine().charAt(0);
while(str.length()>0){
for(int i= 0;i<str.length();i++){
if(str.charAt(i)==userChar)
charCount++;
}
System.out.println("\n The entered character " +"\"" + userChar +
"\" inside " + filename +
"was found " + charCount + " times.\n");
break;
}
}
}
,所以我應該從同時crietrtion去除呢? – LOKI
你可以像喬恩在他的回答中提出的那樣去做。 – Howard