Inserting random numbers into files and reading those randoms numbers - java

I want to insert random numbers into files and read those randoms numbers and store into array in java.
Please review the following piece of code,
import java.io.*;
import java.util.*;
public class sort implements Serializable
{
public static void main(String args[]) throws Exception
{
int[] al;
Random rand=new Random();
Scanner sc=new Scanner(System.in);
File fi=new File("sort.txt");
fi.createNewFile();
FileOutputStream fs=new FileOutputStream(fi);
ObjectOutputStream os=new ObjectOutputStream(fs);
System.out.println("enter how many numbers you need to sort");
int n=sc.nextInt();
al=new int[n];
for(int k=0;k<al.length;k++)
os.write(rand.nextInt(10));
FileInputStream fs1=new FileInputStream("./sort.txt");
ObjectInputStream ois=new ObjectInputStream(fs1);
ois.read();
/* i need to use this file and retrieve the randoms numbers
* from the file and store those numbers from the file and need to sort */
}
}

You might need this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Serializable;
import java.util.Random;
import java.util.Scanner;
public class Sort implements Serializable {
private static final long serialVersionUID = 1L;
private static final File file = new File("sort.txt");
public static void main(String args[]) throws Exception {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
String sCurrentLine;
String[] array = null;
if (!file.exists()) {
file.createNewFile();
}
System.out.println("enter how many numbers you need to sort");
int n = sc.nextInt();
int[] al = new int[n];
try (FileWriter fw = new FileWriter(file);) {
for (int k = 0; k < al.length; k++) {
fw.write(new Integer(rand.nextInt(10)).toString());
}
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((sCurrentLine = br.readLine()) != null) {
array = sCurrentLine.toString().split("");
}
for (int counter = 0; counter < array.length; counter++) {
System.out.println(array[counter]);
}
}
sc.close();
}
}

If you want keep your code.. you can read the values like this:
write:
...
for (int k = 0; k < al.length; k++) {
os.writeInt(rand.nextInt());
}
os.close();
...
read:
FileInputStream fs1 = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fs1);
int[] in = new int[n];
for (int k = 0; k < al.length; k++) {
in[k] = ois.readInt();
//System.out.println(in[k]);
}

Related

When I store my big text file into arraylist the size is only 4?

import java.awt.Graphics;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundEsxception;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Benford {
static Object i = null;
static ArrayList<String> list = new ArrayList<String>();
private static String data;
public static void BenfordPercents() {
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
return;
}
public static void main(String[] args) throws IOException {
DrawingPanel g = new DrawingPanel(500, 500);
Graphics brush = g.getGraphics();
String popData = null;
readCount(popData);
BenfordPercents();
}
public static void readCount(String popdata) throws IOException {
System.out.println("Please make sure the data file is name popData.txt");
System.out.println("We are loading popData.txt...");
Scanner console = new Scanner(System.in);
// Scanner console = new Scanner((new File("popData.txt")));
try {
i = new FileInputStream("popData.txt");
} catch (FileNotFoundException e) {
System.out.println("We cannot locate popData.txt");
System.out.println("Please make sure popData.txt is in the same location" + " as your code file!");
return;
}
System.out.println("popData.txt has loaded!");
System.out.println("");
System.out.println("Please press enter to show data!");
data = console.nextLine();
File file = new File(popdata + ".txt");
FileInputStream fis = new FileInputStream("popdata.txt");
byte[] flush = new byte[1024];
int length = 0;
while ((length = fis.read(flush)) != -1) {
list.add(new String(flush));
// System.out.println(new String(flush));
// System.out.println(list.toString());
}
// Scanner x = new Scanner((new File("popData.txt")));
// while(x.hasNext()){
// list.add(x.next());
// }
fis.close();
}
}
I have a text document with all the numbers of populiation from this link here:
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population
The text document looks like this:
China 1369480000
India 1270250000
United 320865000
Indonesia 255461700
Brazil 204215000
Pakistan 189607000
..etc
..etc
the list is pretty long.
and when I try to store all of these numbers into an array list and I try to print the array list size it just returns 4?
If you want a list-entry for each line, you should prefer a BufferedReader.
FileInputStream fis = new FileInputStream("popdata.txt")
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((String line = br.readLine()) !=null) {
list.add(line);
}
The size of 4 is only the size of your arraylist - each element of your array list was build from an byte-array with a length of 1024. This means that your list either contains about 3K until 4K of data.

reading and writing files into java

I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what
I have:
import java.io.*;
import java.util.Scanner;
public class lab13 {
public static void main(String[] args) throws IOException{
File temp = new File("Lab13.txt");
Scanner file= new Scanner(temp);
PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
writer.println("");
writer.close();
}
}
How do I multiply the numbers by 10 and export it to the new file?
This code is simple as this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("Lab13.txt"));
PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));
while(scan.hasNext()){
print.write(10 * scan.nextInt()+"\n");
}
print.close();
scan.close();
}
}
If the numbers are separated by spaces, use
file.nextInt();
Full Code:
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = file.nextInt();
nums[i] *= 10;
}
after writer.println("");
for(int i = 0; i < 10; i++){
writer.println(nums[i]);
}
I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.
public static void main(String[] args)
{
String toWrite = "";
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
while((line = reader.readLine())!=null){
int x = Integer.parseInt(line);
toWrite += (x*10) + "\n";
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
}catch(Exception e){}
}

Getting file input from two source files

I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.

a file can't be found by the program

I have a file in the same folder of the main class called edges, but when i run it, it said there is an error.
Exception in thread "main" java.io.FileNotFoundException:
What should i change for the program?
import graphs.arrayGraph;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
class underground
{
static int N = 308;
static double [][] edges = new double [N][N];
static String [] stationNames = new String[N];
static ArrayList<String> convert (ArrayList<Integer> m)
{
ArrayList<String> z = new ArrayList<String> ();
for (Integer i:m) z.add(stationNames[i]);
return z;
}
static HashSet<ArrayList<String>> convert (HashSet<ArrayList<Integer>> paths)
{
HashSet <ArrayList <String>> k = new HashSet <ArrayList <String>> ();
for (ArrayList <Integer> p:paths) k.add(convert(p));
return k;
}
public static void main (String[] args) throws Exception
{
for(int i=0; i<N; i++) for (int j=0; j<N; j++) edges[i][j]=0.0;
URL url= underground.class.getResource("edges");
Scanner s = new Scanner (new FileReader(url.getPath()));
String z = s.nextLine();
while (s.hasNext())
{
z = s.nextLine();
String[] results = z.split(",");
edges[Integer.parseInt(results[0])] [Integer.parseInt(results[1])]= 1.0;
edges[Integer.parseInt(results[1])] [Integer.parseInt(results[0])]= 1.0;
}
url= underground.class.getResource("stations");
s = new Scanner(new FileReader(url.getPath()));
z = s.nextLine();
while (s.hasNext())
{
z = s.nextLine();
String[] results = z.split(",");
stationNames[Integer.parseInt(results[0])] = results[3];
}
arrayGraph G = new arrayGraph (edges);
System.out.println(convert(G.shortestPaths(Integer.parseInt(args[0]),Integer.parseInt(args[1]))));
}
}
You have to include the file extension too. Sometimes that may be a problem.
Try edges.txt or whatever the extension is.
Pass an InputStream into the Scanner. Don't use a FileReader.
i.e., change this:
URL url= underground.class.getResource("edges"); // are you sure the name is correct?
Scanner s = new Scanner (new FileReader(url.getPath()));
to this:
InputStream is = underground.class.getResourceAsStream("edges");
Scanner s = new Scanner(is);

Array Required, but found Int

I'm running into an issue when converting some code for another project and was hoping for a bit of help. In the 'readFile' method, I am trying to parse a String to integers when I read the file. However, it is giving me the error 'array found, but int required'
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
matrix is an array of type int, which means matrix[lineCount] is an int.
You are tryng to do matrix[lineCount][i] which is getting the place i of an int.
That is why you are getting that error.
I guess you wanted matrix to be int[][] matrix = new int[10][10];
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
is wrong.
Should be either
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);

Categories