random generator returning multiple results - java

The code reads from text file and goes true all 1000 words in txt. It then read each word calculate ist lenght and from that lenght gets random number (say lenght is 4 and random would be 2). It then replaces that random numbers character with "*". This would be later used as an sample into main program.
Problem is at the moment i am getting same as an result multiple times.
TXT:
http://textuploader.com/oyfi
public class random_2 {
public static void main(String[] args) {
int dolzina = 0;
Object s;
String outputFile = "random_2.txt";
ArrayList<String> list = new ArrayList();
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
list.add(vrstica);
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx <= list.size(); ++idx) {
String test=list.get(idx);
dolzina=test.length();
Random randomGenerator = new Random();
for (int i = 0; i<= dolzina; ++i) {
int randomInt = randomGenerator.nextInt(dolzina);
StringBuilder beseda = new StringBuilder(test);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
}
}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

You must use the constructor
Random(long seed)
A random generator can be view as an object that have a predefined list number, and returning at each call the next number into the list.
Using the Random(long seed) will give the first index to start with into the list.
Here into your code, you always start the random list at position 0.
Concretely, we use for the 'seed' parameter the actual time in millisecond. So each time you run your program, you will initalize the random generator with a different start index, and you will get a different result each run time.

Related

Reading data from file without manually inputing the length it the array

Please I will like to adjust this code that reads integers from a file.
I will like the code to detect the number (n) of the dataset instead of having to put in figures manually as done below (4000 )
double[] tall = new double[4000];
public class Extracto {
public static void main(String[] args) throws IOException {
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
double[] tall = new double[4000];
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Double.parseDouble(s); // This is line 19.
// System.out.println(tall[i]);
s = in.readLine();
i++;
}
I am expecting the adjusted code to obtain the data length without manually putting it in like in as shown in the code below for the 4000 length.
double[] tall = new double[4000];
As Thomas mentioned, use a list, instead of an array.
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
ArrayList<Double> tall = new ArrayList<>();
while(in.ready()){
String s = in.readLine().trim();
if(!s.isEmpty()){
tall.add(Double.parseDouble(s);
}
}
your codes can be further compacted if you use a list.
also do add a try-catch in the event when the String read is not a number.

Using Buffered Reader to add user input to an array

I use a buffered reader to read in the input and then it adds it to an array. But for some reason it only adds the last input to the array. I also want to check if the first input is zero... so thats what I am doing with the check variable. But the main problem is that it doesn't add it to the array.
public static void main (String[] Args) throws IOException
{
int[] numbers = new int[100];
Scanner scan = new Scanner(System.in);
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bReader;
bReader = new BufferedReader(isReader);
int intNumber = Integer.parseInt(bReader.readLine());
int check = scan.nextInt();
while (check != 0)
{
int i = 0;
numbers[i] = Integer.parseInt(bReader.readLine());
check = intNumber;
i++;
}
bReader.close();
}
move int i = 0 outside of while loop. In each iteration i is getting initialized to 0 so your array is having only one value and that is in 0th index

How can I read only one thing in from a textfile?

I can read in from the file and am able to change the amount of lines given by changing the number in the for loop but I don't want all the numbers in my file displayed side by side like that. I need them all going down one by one randomly.
public class Assignment2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
for (int p = 0; p<3; p++)
{
String randomString = lines.get(r.nextInt(2));
System.out.println(lines);
}
}
}
I think what you want to print is
String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);
To display only the first 20 random lines from this list of maybe 100
for (int i = 0; i < 20; i++) {
int rowNum = r.nextInt(lines.size ());
System.out.println(lines.get(rowNum);
}

How to read N amount of lines from a file?

I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.
Say for example, the file contains 1-100 numbers, like so;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.
ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));
for (double i = 0; i <= 5; ++i) {
// I know I need to add something here so the for loop read through
// the file but I have no idea how I can do this
array.add(i); // This is saying read 1 line and add it to arraylist,
// then read read second and so on
}
You could try using a Scanner and a counter:
ArrayList<Double> array = new ArrayList<Double>();
Scanner input = new Scanner(new File("numbers.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 10)
{
array.add(Double.parseDouble(input.nextLine()));
counter++;
}
This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.
See this How to read a large text file line by line using Java?
I think this will work:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
if (i < 5)
{
// process the line.
i++;
}
}
br.close();
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
System.err.println(ex.toString());
//here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
//read line by line with the readLine() method
while ((line = reader.readLine()) != null && counter < N) {
//check also the counter if it is smaller then desired amount of lines to read
array.add(line); //add the line to the ArrayList of strings
counter++; //update the counter of the read lines (increment by one)
}
//the while loop will exit if:
// there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
// OR the desired amount of line was correctly read
reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
System.err.println(ex.toString());
}
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("numbers.txt")))) {
for (int i = 0; i < 5; ++i) { // Loops 5 times
String line = in.readLine();
if (line == null) [ // End of file?
break;
}
// line does not contain line-ending.
int num = Integer.parseInt(line);
array.add(i);
}
} // Closes in.
System.out.println(array);
You can do this with:
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
// do something with the list here
}
As complete example as JUnit test:
public class ReadFirstLinesOfFileTest {
#Test
public void shouldReadFirstTenNumbers() throws Exception {
Path p = Paths.get("numbers.txt");
Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
}
}
}
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
myList.add(fileScanner.nextDouble());
}
Make sure you have "numberOfLinesToRead" lines in your file.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> nlines = IntStream.range(0, hlines)
.mapToObj(i -> readLine(br)).collect(Collectors.toList());
String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

JAVA Integer Trouble

I have written a sorting algorithm (bubble) and I have used 10000 unique values i.e.
int BubArray[] = new int[]{#10000 unique unsorted values#};
I was wondering how I would put the integers into a file and call the file instead of the 10000 integers in the code.
Also in which format would they go (with commas, spaces?) I'm not sure.
Any help would be appreciated, thanks.
This is not correct answer, just hint how to use file, but you can modify the code and make it usable according to your need.
try {
String str;
String[] temp;
BufferedReader br = new BufferedReader(new FileReader("your filepath"));
while ((str= br.readLine()) != null) {
temp = str.split(";"); // seperator words bye;
System.out.println(str);
for(int i = 0; i<temp.lenght; i++)
System.out.println(temp[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Assuming you need some random numbers to test your sort method:
int amount = 1000;
int[] array = new int[amount];
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt();
}
If you want to give input 1000 different unique values Random is not an good idea. Random can give same value more than once.
Put it in a File separated by line breaks and use a Scanner to read line by line, putting them into an array.
An example taken from Scanner documentation page:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
You can easily modify it to get int instead of long using hasNextInt() and nextInt() methods.

Categories