试图将随机字符串放入文件中
Trying to put random strings into a file
我正在尝试将随机字符串插入到 .txt 文件中。我的代码如下:
import java.util.*;
import java.io.*;
class fileProcessing{
public static void main (String[] args) throws Exception{
letter();
}
public static void letter() throws Exception{
int count = 0;
PrintStream out = new PrintStream(new File("nums.txt"));
while (count < 7 ){
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122 - 97) + 1);
char a = (char)randomNum;
out.print(a);
count++;
}
}
}
我尝试将一行 7 个随机字母放入一个 .txt 文件中大约 400 次左右。我的代码只允许我输入一行 7 个字母。我不确定如何获得其他 399 行。任何帮助将不胜感激。谢谢!
使用包含您已编写的循环的 nested loop
。它所做的是,在你生成一个词之后,进行一次新的迭代,在你的文件中写入另一个词。
import java.util.*
import java.io.*;
class FileProcessing
{
public static void main(String[] args) throws IOException
{
letters();
}
public static void letters() throws IOException
{
int count;
PrintStream out = new PrintStream(new File("nums.txt"));
/*Outer loop. When the loop on the inside finishes generating
*a word, this loop will iterate again.
*/
for(int i=0; i<400; ++i)
{
count=0;
/*your current while loop*/
while (count < 7)
{
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122-97)+1);
char a = (char) randomNum;
out.print(a);
count++;
}
//print new line so all words are in a separate line
out.println();
}
//close PrintStream
out.close();
}
}
在此处了解有关嵌套循环的更多信息:http://www.javawithus.com/tutorial/nested-loops
我正在尝试将随机字符串插入到 .txt 文件中。我的代码如下:
import java.util.*;
import java.io.*;
class fileProcessing{
public static void main (String[] args) throws Exception{
letter();
}
public static void letter() throws Exception{
int count = 0;
PrintStream out = new PrintStream(new File("nums.txt"));
while (count < 7 ){
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122 - 97) + 1);
char a = (char)randomNum;
out.print(a);
count++;
}
}
}
我尝试将一行 7 个随机字母放入一个 .txt 文件中大约 400 次左右。我的代码只允许我输入一行 7 个字母。我不确定如何获得其他 399 行。任何帮助将不胜感激。谢谢!
使用包含您已编写的循环的 nested loop
。它所做的是,在你生成一个词之后,进行一次新的迭代,在你的文件中写入另一个词。
import java.util.*
import java.io.*;
class FileProcessing
{
public static void main(String[] args) throws IOException
{
letters();
}
public static void letters() throws IOException
{
int count;
PrintStream out = new PrintStream(new File("nums.txt"));
/*Outer loop. When the loop on the inside finishes generating
*a word, this loop will iterate again.
*/
for(int i=0; i<400; ++i)
{
count=0;
/*your current while loop*/
while (count < 7)
{
Random rand = new Random();
int randomNum = 97 + rand.nextInt((122-97)+1);
char a = (char) randomNum;
out.print(a);
count++;
}
//print new line so all words are in a separate line
out.println();
}
//close PrintStream
out.close();
}
}
在此处了解有关嵌套循环的更多信息:http://www.javawithus.com/tutorial/nested-loops