When I run the program, the smallest number always turns out to be 0. Why is this? The largest and average values seem to be correct.
The problem most likely lies in how I am using the random class.
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class ReadAndWrite {
public static void main(String[] args) {
Random ran = new Random();
int i_data = 0;
int[] sort = new int[100];
File file = new File("Test4");
int total = 0;
int average = 0;
try {
file.createNewFile();
}
catch(Exception e) {
System.out.println("Could not create the file for some reason. Try again.");
System.exit(0);
}
try {
FileOutputStream fos = new FileOutputStream("Test4");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i <= 100; i++) {
int x = ran.nextInt(100);
oos.writeInt(x);
}
oos.close();
}
catch(IOException e) {
System.out.println("Whoops");
}
try {
FileInputStream fos = new FileInputStream("Test4");
ObjectInputStream ooss = new ObjectInputStream(fos);
for (int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
}
Arrays.sort(sort);
for(int i = 0; i < 100; i++) {
total = total + sort[i];
average = total/100;
}
System.out.println("The largest number in the file is: " + sort[99]);
System.out.println("The smallest number in the file is: " + sort[0]);
System.out.println("The average number in the file is: " + average);
ooss.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
You are sorting the array as you read each value.
for(int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
Arrays.sort(sort);
}
This means you start with [1, 0, 0, 0, ...] but after sorting you have [0, 0, 0, ... 1 ]
This is where a debugger would help you debug your program. The solution is to only sort the array after you have read it.
A simpler solution is to write and read the array in one go instead of using a loop.
BTW: Unless you are writing/reading objects you don'#t need to be using ObjectOutputStream and it has an overhead compared with say DataOutputStream.
As #KevinEsche points out, if you have 100 random values of 0 to 99 there is a good chance that one of them will be 0, though not every time.
A shorter implementation could look like this
public static void main(String[] args) throws IOException {
Random rand = new Random();
int samples = 100;
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("test"))) {
out.writeInt(samples);
for (int i = 0; i < samples; i++)
out.writeInt(rand.nextInt(100));
}
int[] sort;
try (DataInputStream in = new DataInputStream(new FileInputStream("test"))) {
int len = in.readInt();
sort = new int[len];
for (int i = 0; i < len; i++)
sort[i] = in.readInt();
}
IntSummaryStatistics stats = IntStream.of(sort).summaryStatistics();
System.out.println("The largest number in the file is: " + stats.getMax());
System.out.println("The smallest number in the file is: " + stats.getMin());
System.out.println("The average number in the file is: " + stats.getAverage());
}
Related
My program stimulates FCFS scheduling algorithm. It takes a .csv file as input and output the average waiting time. I have trouble with inputting the file. This is the error that i get when i ran the code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at main.FCFS.main(FCFS.java:16)
What am I doing wrong? I cannot seems to figure it out. Please help.
package main;
//programming FCFS scheduling algorithm
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class FCFS {
public static void main(String[] args) throws FileNotFoundException {
// To Store Name of the file to be opened
String file = args[0];
int i = 0, n;
double AWT = 0, ATT = 0;
int AT[] = new int[100];
int BT[] = new int[100];
int WT[] = new int[100];
int TAT[] = new int[100];
int PID[] = new int[100];
// To open file in read mode
FileInputStream fin = null;
// To read input(file name) from standard input stream
Scanner s = new Scanner(new File("/Users/SLO/ex.csv"));
// To hold each single record obtained from CSV file
String oneRecord = "";
try {
// Open the CSV file for reading
fin = new FileInputStream(file);
// To read from CSV file
s = new Scanner(fin);
// Loop until all the records in CSV file are read
while (s.hasNextLine()) {
oneRecord = s.nextLine();
// Split record into fields using comma as separator
String[] details = oneRecord.split(",");
PID[i] = Integer.parseInt(details[0]);
AT[i] = Integer.parseInt(details[1]);
BT[i] = Integer.parseInt(details[2]);
System.out.printf("Process Id=%d\tArrival Time=%d\tBurst Time=%d\n", PID[i], AT[i], BT[i]);
i++;
}
WT[0] = 0;
for (n = 1; n < i; n++) {
WT[n] = WT[n - 1] + BT[n - 1];
WT[n] = WT[n] - AT[n];
}
for (n = 0; n < i; n++) {
TAT[n] = WT[n] + BT[n];
AWT = AWT + WT[n];
ATT = ATT + TAT[n];
}
System.out.println(" PROCESS BT WT TAT ");
for (n = 0; n < i; n++) {
System.out.println(" " + PID[n] + " " + BT[n] + " " + WT[n] + " " + TAT[n]);
}
System.out.println("Avg waiting time=" + AWT / i);
System.out.println("Avg waiting time=" + ATT / i);
} catch (FileNotFoundException e) {
System.out.printf("There is no CSV file with the name %s", file);
}
finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Well, an ArrayIndexOutOfBoundsException is thrown if there are no arguments, because you access the empty array at a non existing index. Add the following lines to check if the argument is passed correctly:
...
public static void main(String[] args) throws FileNotFoundException {
if (args.length == 0)
throw new IllegalArgumentException("Missing mandatory file name in argument list");
// To Store Name of the file to be opened
String file = args[0];
...
If the missing argument ist the reason for the failure, check out https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html to find out how to pass it properly.
Sorry for click bait title, but it is my problem, and I can't really change to wording without losing the question.
I have the following code which is meant to select a file, read it, and find it's mode, and I think I got it done, but I have one issue
public class ModeFinder
{
public static int countDoubles(File file) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
int count = 0;
while (reader.hasNextDouble())
{
count++;
reader.nextDouble();
}
reader.close();
return count;
}
public static void main(String args[]) throws FileNotFoundException
{
String filename;
FileDialog filePicker = new FileDialog(new JFrame());
filePicker.setVisible(true);
filename = filePicker.getFile();
String folderName = filePicker.getDirectory();
filename = folderName + filename;
System.out.println("filename = " +filename);
File inputFile = new File(filename);
Scanner fileReader = new Scanner (inputFile);
int maxValue = 0,
maxCount = 0;
int[] a = new int[countDoubles(inputFile)];
while (fileReader.hasNextInt())
{
for (int i = 0; i < a.length; i++)
{
int count = 0;
for (int j = 0; j < a.length; j++)
{
if (a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
}
System.out.println("The most common grade is: " +maxValue);
}
}
The last bit with the most common grade doesn't even print and I don't know why.
You aren't calling nextInt to get the value from the file so your while loop is going to loop forever. You need something like:
while (fileReader.hasNextInt())
{
int value = fileReader.nextInt();
...
I'm trying to write a program that reads a file of an array (arranged with the Rows as the first character, and the Columns as the next character, and then a box of RxC terms) and tries to determine if five characters next to each other horizontally, vertically, or either way diagonally are the same, to color differently (in my GUI main program)
The code is EXTREMELY slow, and only works for smaller arrays? I don't understand what I'm doing wrong.
The Files look like this:
5 4
1 2 3 4 5
1 2 3 4 5
7 3 2 0 1
6 1 2 3 5
Code:
public class fiveinarow
{
int[][] Matrix = new int [100][100];
byte[][] Tag = new byte [100][100];
int row, col;
String filepath, filename;
public fiveinarow()
{
row = 0;
col = 0;
filepath = null;
filename = null;
}
public void readfile()
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
filepath = chooser.getSelectedFile().getPath();
filename = chooser.getSelectedFile().getName();
}
try
{
Scanner inputStream = new Scanner(new FileReader(filepath));
int intLine;
row = scan.nextInt();
col = scan.nextInt();
for (int i=0; i < row; i++)
{
for (int j = 0 ; j < col; j++)
{
int[][]Matrix = new int[row][col];
Matrix[i][j] = inputStream.nextInt();
}
}
}
catch(IOException ioe)
{
System.exit(0);
}
}
When I compute a 7x7, I get confirmation of opening and processing gives an array (7x7) of all Zeroes.
When I compute a 15x14, I get "Exception in thread "AWT-EventQueue-0" errors and no array when processed.
Some suggestions:
Create a method that returns int[][] to read in your input file
After reading the row and column, create the matrix int[][] result = new int[row][column];
inside your loop, read each integer into the matrix (result[i][j] = scan.nextInt();
Don't forget to move to the next line after scanning all the numbers on one line'
You might use something like:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class ReadMatrix {
static ReadMatrix mReadMatrix;
int[][] matrix;
int row, col;
String filepath, filename;
/**
* #param args
*/
public static void main(String[] args) {
mReadMatrix = new ReadMatrix();
mReadMatrix.readfile();
}
// int[][] Matrix = new int [100][100];
// byte[][] Tag = new byte [100][100];
public void readfile() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filepath = chooser.getSelectedFile().getPath();
filename = chooser.getSelectedFile().getName();
}
Scanner inputStream;
try {
inputStream = new Scanner(new FileReader(filepath));
row = inputStream.nextInt();
col = inputStream.nextInt();
System.out.println(" matrix is " + row + " rows and " + col + " columns");
matrix = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = inputStream.nextInt();
System.out.println(" " + i + "," + j + ": " + matrix[i][j]);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You might want to check out something similar that I did:
Loading Tile Maps From Text Files In Slick2D
or
Why Aren't My Tile Maps Displaying Correctly?
I have assignment question I could not get the final answer.
the question was :
Write a program that will write 100 randomly generated
integers to a binary file using the writeInt(int) method in
DataOutputStream. Close the file. Open the file using a
DataInputStream and a BufferedInputStream. Read the integer
values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average
of the numbers.
I believe I done first part of the question which is (write into file), but I don't know how to report the sum.
so far that what I have
import java.io.*;
public class CreateBinaryIO {
public static void main(String [] args)throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("myData.dat"));
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
output.close();
}
}
This ReadBinaryIO class:
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws IOException {
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int value = input.readInt();
System.out.println(value + " ");
input.close();
}
}
Try to divide the problem in parts to organice your code, don't forget to flush the OutputStream before you close it.
package javarandomio;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class JavaRandomIO {
public static void main(String[] args) {
writeFile();
readFile();
}
private static void writeFile() {
DataOutputStream output=null;
try {
output = new DataOutputStream(new FileOutputStream("myData.txt"));
Random rn = new Random();
for (int i = 0; i <= 100; i++) {
output.writeInt(rn.nextInt(100));
}
output.flush();
output.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
output.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
private static void readFile() {
DataInputStream input=null;
try {
input = new DataInputStream(new FileInputStream("myData.txt"));
int cont = 0;
int number = input.readInt();
while (true) {
System.out.println("cont =" + cont + " number =" + number);
if (input.available() == 4) {
break;
}
number = input.readInt();
cont++;
}
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
input.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
That's not generating a random number. Look into java.util.Random.nextInt().
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
That wil actually break because you are using i<=100 instead of just i<100 but I'm not sure why you are populating that array to begin with? Also, that code just writes the same number 101 times. The generation of that random number needs to be within the loop so a new one is generated each time.
As far as reading it back, you can loop through your file by using a loop like this:
long total = 0;
while (dataInput.available() > 0) {
total += dataInput.readInt();
}
Try below code where you are trying to read one integer:
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int sum = 0;
for(int i =0; i<=100; i++){
int value = input.readInt();
sum += value;
}
System.out.println(value + " ");
input.close();
Or if you want to dynamically set the lenght of the for loop then
create a File object on myData.dat file and then divide the size of file with 32bits
File file = new File("myData.dat");
int length = file.length() / 32;
for(int i =0; i <= length;i++)
So far I submit the assignment and I think I got.
/** Munti ... Sha
course code (1047W13), assignment 5 , question 1 , 25/03/2013,
This file read the integer values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average of the numbers.
*/
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws ClassNotFoundException, IOException {
//call the file to read
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
// total to count the numbers, count to count loops process
long total = 0;
int count = 0;
System.out.println("generator 100 numbers are ");
while (input.available() > 0) {
total += input.readInt();
count ++;
System.out.println(input.readInt());
}
//print the sum and the average
System.out.println("The sum is " + total);
System.out.println("The average is " + total/count);
input.close();
}
}
CreateBinaryIO Class:
import java.io.*; import java.util.Random;
public class CreateBinaryIO { //Create a binary file public static
void main(String [] args)throws ClassNotFoundException, IOException {
DataOutputStream output = new DataOutputStream(new
FileOutputStream("myData.dat"));
Random randomno = new Random();
for(int i=0;i<100;i++){ output.writeInt(randomno.nextInt(100)); }// Loop i closed output.close(); } }
What I need to do is to implement the 0-1 Knapsack problem. There is an input file named "In0302.txt" and an output file named "Out0302.txt". The program gets values from INPUT file and saves the results to OUTPUT file. I got my input values on paper from my "dr".
Putting them to the file seems to be ok in OUTPUT file. But... on classes "dr" tried to put other values in INPUT file, but the program didn't work. What is more there was no even an error, but the program was still compiling and compiling... and I can't get know where the problem is. Does anybody would try to change something in this code or tell me what is wrong ?
INPUT:
4 6
2 1
3 2
3 4
4 5
OUTPUT:
1 4
2 3
JAVA CODE:
public class Knapsack {
public static int max(int a, int b){
if (a > b){
return a;
}
else{
return b;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args){
int n = 0, W = 0, p[] = null, w[] = null, S[][] = null, S_object[][] = null;
//s[][] = arrays with values
try {
FileReader fr = new FileReader("In0302.txt");
BufferedReader in = new BufferedReader(fr);
String line = in.readLine();
String[] cols = line.split(" ");
n = Integer.parseInt(cols[0]); W = Integer.parseInt(cols[1]);
p = new int[n+1]; w = new int[n+1];
int k = 1;
while ((line = in.readLine()) != null) {
cols = line.split(" ");
p[k] = Integer.parseInt(cols[0]);
w[k] = Integer.parseInt(cols[1]);
k++;
}
S = new int[W+1][n+1];
S_object = new int[W+1][n+1];
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
if (i == 0){
S[weight][i] = 0;
S_object[weight][i] = 0;
}
else if (weight < w[i]){
S[weight][i] = S[weight][i-1];
S_object[weight][i] = S_object[weight][i-1];
}
else if (weight >= w[i-1]){
S[weight][i]=max(S[weight][i-1],S[weight-w[i]][i-1]+p[i]);
if ((max(S[weight][i-1], S[weight-w[i]][i-1] + p[i]) == (S[weight-w[i]][i-1] + p[i]))) {
S_object[weight][i]=i;
} //added new element to bag
else {
S_object[weight][i]=S_object[weight][i-1];
} //nothing has been added
}
}
}
in.close();
fr.close();
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
File outputFile;
FileWriter out;
try{
outputFile = new File("Out0302.txt");
out = new FileWriter(outputFile);
String line = "";
int max_value = S[W][n];
for (int m = n; m > 0; m--){
if (S[W][m] == max_value){
line = " " + S_object[W][m] + "";
int temp = W;
while ((temp-w[S_object[temp][m]]) > 0){
temp = temp - w[S_object[temp][m]];
line += " " + S_object[temp][m];
}
out.write(line + "\n");
out.write("\n\t");
}
}
out.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
System.out.println("Arrar of values:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S[weight][i] + " ");
}
System.out.println("");
}
System.out.println("Array of objects:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S_object[weight][i] + " ");
}
System.out.println("");
}
}
}