我需要使用Java I/O将100个随机创建的整数随机创建

  • 本文关键字:随机 创建 100个 整数 Java java
  • 更新时间 :
  • 英文 :


我需要使用Java I/O随机编写100个整数创建的整数到目前为止,这是我的代码:

package lab;
import java.util.*;
import java.io.*;
public class test {
    public static void main(String[] args) {
        Random num = new Random();
        try {
            File file = new File("E:\Test.txt");
            if(file.exists()) {
                file.createNewFile();
        }
        PrintWriter out = new PrintWriter(new File("E:\Test.txt"));
        for (int i = 0; i <= 9; i++){
             output.print(num.nextInt(100)+" "+num.nextInt(100) + " " +
            num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
            + num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
            + num.nextInt(100) + " " + num.nextInt(100));
            output.println();
        }
        out.close();
        Scanner input = new Scanner(file);
        while(input.hasNext()) {
            System.out.println(input.nextLine());
        }
        input.close();
        }
        catch (IOException ex) {
            System.out.println("File Already Exists!");
        }
    }
}

我需要简化" for-loop",并能够读取文件以显示它。谁能帮忙?

首先,请勿在循环中加和串联字符串(创建新对象),请使用StringBuilder。

用随机数构建字符串后,以这样的保存:http://www.mkyong.com/java/how-to-write-to-write-to-file-in-java-bufferdriter-example/

StringBuilder str = new StringBuilder();
Random rng = new Random();
for (int i = 0; i < 100; ++i)
    str.append(rng.nextInt(100) + " ");
System.out.println(str.toString());

System.out.println(str.toString());替换为您的filestream写作。

 File file = new File("File_name.txt");
 StringBuilder str = new StringBuilder();
 try (PrintWriter output = new PrintWriter(file);) {
      for (int i = 0; i < 100; i++) {
          int num = ((int)(Math.random() * 500) + 1);    
          output.print(num);
          output.print(" ");
          str.append(num + " ");
     }
}
System.out.println(str.toString());

最新更新