Java (Write/read data) Write a program to create a file named t if t does not ex
ID: 3716523 • Letter: J
Question
Java
(Write/read data) Write a program to create a file named t if t does not exist. Write 100 integers created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display the data in increasing order. Make sure you use the File class Make sure you use the Scanner class Make sure you use the Auto File Chose technique outlined in 12.11.2 when writing a file. don't forget to put your name and the assignment info in the comments section of your code. don't forget to put your name on the zilp file.Explanation / Answer
Generate100RandNumbers.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Generate100RandNumbers {
public static void main(String[] args) {
//Declaring variables
int size=100,k=0;
//Creating an integer Array of size 100
int randNos[]=new int[size];
//Creating a random Class object
Random r = new Random();
try {
//Writing 100 random numbers into file
FileWriter fw=new FileWriter(new File("RandNos.txt"));
for(int i=1;i<=100;i++)
{
int num=r.nextInt(1000) + 1;
fw.write(num+" ");
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Reading the numbers from file and populate those values into an array
Scanner sc=new Scanner(new File("RandNos.txt"));
while(sc.hasNext())
{
randNos[k]=sc.nextInt();
k++;
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//calling the methods
randNos=sort(randNos);
display(randNos);
}
//This method will display the array elements
private static void display(int[] randNos) {
System.out.println(" Displaying the numbers in Ascending order :");
for(int i=1;i<=100;i++)
{
System.out.print(randNos[i-1]+" ");
if(i%10==0)
System.out.println();
}
}
//This method will sort the array elements in ascending order
private static int[] sort(int[] randNos) {
//This Logic will Sort the Array of elements in Ascending order
int temp;
for (int i = 0; i < randNos.length; i++)
{
for (int j = i + 1; j < randNos.length; j++)
{
if (randNos[i] >randNos[j])
{
temp = randNos[i];
randNos[i] = randNos[j];
randNos[j] = temp;
}
}
}
return randNos;
}
}
_________________
Output:
Displaying the numbers in Ascending order :
1 10 12 34 43 48 60 61 65 67
75 80 87 91 128 153 156 158 169 174
176 177 202 222 227 231 244 246 248 265
266 266 279 282 288 292 297 306 318 333
333 337 341 356 359 374 377 381 390 395
401 401 402 404 413 439 439 449 456 462
470 480 486 511 520 542 559 564 598 628
635 642 652 657 693 695 696 704 721 728
801 809 810 826 839 842 854 862 881 887
893 895 905 920 921 937 943 973 984 990
____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.