我正在編寫一個程序來更改輸入文件。它應該開始一個新的行後? 。和!但我似乎無法弄清楚。每一個新行也應該以我認爲我得到的大寫字母開頭。它也應該消除我也相信我得到的不必要的空間。如何在句號,問號和感嘆號之後開始換行?
例如:你好?酒保。我可以喝一杯威士忌嗎?
Output should be:
Hello?
Bartender.
Can I have a drink!whiskey please.
它應該只在這些運算符後面加一個空格後再換行。如果沒有空間,它不會換新線。
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String fileName, answer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Test Input File:");
fileName = keyboard.nextLine();
File file = new File(fileName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(file);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file" + file);
System.exit(0);
}
System.out.println("Enter a line of text:");
String line = keyboard.nextLine();
outputStream.println(line);
outputStream.close();
System.out.println("This line was written to:" + " " + file);
System.out.println(" ");
TextFileProcessor.textFile();
}
}
二等
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Test Input File:");
String inputFile = keyboard.next();
System.out.print("Output File:");
String outputFile = keyboard.next();
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(inputFile));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputFile));
String line = inputStream.readLine();
line = line.replaceAll("\\s+", " ").trim();
line = line.substring(0,1).toUpperCase() + line.substring(1);
//This is where I would like to add code
while(line != null)
{
outputStream.println(line);
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + inputFile + " not found");
}
catch(IOException e)
{
System.out.println("Error reading from file" + inputFile);
}
}
}
它的工作!非常感謝!我現在唯一的問題是新行不以大寫字母開頭。我以爲我解決了這個問題。有任何想法嗎? –
@ nedst3r修復它 – ritesht93
我很欣賞反饋。儘管如此,我無法使用循環來處理我的代碼。我不知道爲什麼。我收到很多錯誤 –