I want to take user input in string and write that string in a text file using java. But there is a problem

huangapple 未分类评论72阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2020年8月14日 19:45:31
  • 转载请务必保留本文链接:https://java.coder-hub.com/63412144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定