我知道这很容易修复,但我已经和它争斗了一个小时。我需要不断地从用户那里获取文字,直到他们输入“退出”并将其写入过程中的文件。但问题出在这里,它出现了“输入单词:”然后我输入它然后点击输入它不会采取它直到我写第二次然后它工作并使用第二个。
//@Author: Tyler Cage
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class week12Program1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
//declaring the writer and initlizing it
FileOutputStream fileByteStream = new FileOutputStream("C:/Users/tyl3r/Desktop/test.txt");
PrintWriter outFS = new PrintWriter(fileByteStream);
Scanner scnr = new Scanner(System.in);
//declainrg ints
int i = 0;
//open file and print
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next());
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
}
}
}
答案 0 :(得分:1)
本段代码中的问题:
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next()); // first time scanning input
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){ // second time scanning input
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
实际上你正在读取输入2次,所以你需要再输入一次这个词才能得到预期的结果。
要解决这个问题,你只需要声明变量来保存输入,然后在if条件下检查变量内容:
while(i<1){
System.out.println("Enter word: ");
String word = scnr.next();
outFS.println(word);
outFS.flush();
if(word.equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}