英文:
I want to take user input in string and write that string in a text file using java. But there is a problem
问题
import java.io.*;
import java.util.Scanner;
public class FileHandlingReadingWriting {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        FileWriter fWrite = new FileWriter("IOPinJava.txt");
        String input = "";
        System.out.println("Enter data to be entered in the string\n");
        input = sc.next();
        String i = input;
        fWrite.write(i);
        fWrite.flush();
        fWrite.close();
   }
}
当我执行这段代码并输入一个字符串时,只有字符串的第一个单词被写入文件。如果字符串是 "This is a text",那么只有 "This" 会被写入到文本文件中。
英文:
import java.io.*;
public class FileHandlingReadingWriting {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        FileWriter fWrite = new FileWriter("IOPinJava.txt");
        String input = "";
        System.out.println("Enter data to be entered in the string\n");
        input = sc.next();
        String i = input;
        fWrite.write(i);
        fWrite.flush();
        fWrite.close();
   }
}
when I execute this code and enter a string, only first word of the string gets written in the file. If the string is "This is a text", then only "This" gets written to the text file.
答案1
得分: 0
You aren't reading in the entire line with your scanner. Try  input = sc.nextLine()
英文:
You aren't reading in the entire line with your scanner. Try  input = sc.nextLine()
专注分享java语言的经验与见解,让所有开发者获益!

评论