Finding largest value in an array from a text file - java

I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.

First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}

Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}

Related

Bubble sort lines of a file (Java)

I am trying to find a way to bubble sort a text file that looks like this:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in the order of release date for example a game released on 01/25/16 would come before a game released in 06/26/16 and it would create a new file like this:
04/26/16 Sega 3D Classics Collection
06/24/16 Tokyo Mirage Sessions #FE
07/14/16 Batman: Arkham Underworld
I am certain that there will be a for loop involved as each line will be an element of an array with swapping methods and a temporary value for comparison sake to swap the order of the but I cannot think of a way to write the new order into a new file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String[]arr;
arr = input(file);
output(file,arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
}
Just invoke the sortByMonth inside your output method:
Also, there is no need to pass the File object to output as it is not used.
public static void output(String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}

Timed Out and NZEC on CodeChef Problem NUKES

While trying out the problem "Nuclear Reactors" , i'm getting the results on my computer ,but in CodeChef there is a timelimit of 0.2 secs and while submitting my answer i'm getting a TLE(time limit exceeded) error and in one test i'm getting wrong answer.
I don't have a clue what is causing this.
Any hints would be helpful.
Link :https://www.codechef.com/problems/NUKES
My code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) {
FastReader fr = new FastReader();
// I/P
int a = fr.nextInt();
int n = fr.nextInt();
int k = fr.nextInt();
// ARRAY TO STORE RESULT
int react[] = new int[k];
// ARRAY OF ZERO AND ONES
int temp_one[]=new int[k];
int temp_zero[]=new int[k];
for (int i = 0; i < k; i++){
react[i] = 0;
temp_zero[i]=react[i];
temp_one[i]=1;
}
while (a != 0) { // TO REPEAT TILL ALL (A) ARE USED
int j = 0;
while(react[j]>=n){ // CHECK(value in K>=A)
react[j] = 0;
j++;
}
react[j]++;
if(Arrays.equals(react,temp_one)){ // CHECK(all K are filled)
react=temp_zero;
}
a--;
}
for(int i=0;i<k;i++){
System.out.print(react[i]+" ");
}
}
//////////////////// FAST IO //////////////////////
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Results given by CodeChef
This code should work for your algorithm.
int[] ret = new int[k];
for(int i = (int)(Math.log(a)/Math.log(n+1)); i >= 0; i--) {
int val = (int)(a/Math.pow(n+1,i));
a -= val*Math.pow(n+1,i);
if (i < k) ret[i] = val;
}
ret is your return array.
It basically finds the base n+1 representation of a, which is the answer they want you to get. If you want more information on why it works, feel free to ask!

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

Reading a .dat file into an array in Java

The code that I'm writing has two classes: writeInts and readInts. I wrote writeInts to randomly generate 100 numbers between 0 and 1000 and output them to a data.dat file.
readInts is supposed to open a DataInputStream object and read in the "raw" data from the data.dat file and store the 100 integers in an array. My problem is that I can't seem to read the data correctly. Any help with this would be greatly appreciated. Thanks!
writeInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
int num = 0 + (int)(Math.random());
int[] counts = new int[100];
for(int i=0; i<100; i++) {
output.writeInt(num);
counts[i] += num;
System.out.println(num);
}
output.close();
}
}
readInts:
import java.io.*;
import java.util.*;
public class ReadInts {
public static void main(String[] args) throws IOException {
// call the file to read
Scanner scanner = new Scanner(new File("data.dat"));
int[] data = new int[100];
int i = 0;
while (scanner.hasNextInt()) {
data[i++] = scanner.nextInt();
System.out.println(data[i]);
scanner.close();
}
}
}
If you want to write binary data, use DataInputStream/DataOutputStream. Scanner is for text data and you can't mix it.
WriteInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
output.writeInt(i);
System.out.println(i);
}
output.close();
}
}
ReadInts:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadInts {
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(new FileInputStream(
"data.dat"));
while (input.available() > 0) {
int x = input.readInt();
System.out.println(x);
}
input.close();
}
}
More. If you want to generate a random number in range from 0 to 1000 (both inclusive), you use this statement:
int rndNum = (int) (Math.random() * 1001);
It works that way: Math.random() generates a double in range from 0 to 1 (exclusive), which you then should map to integer range and floor. If you want you maximal value to be 1000, you multiply it by 1001 - 1001 itself is excluded.
Yep, like that:
import java.io.*;
public class WriteRandomInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
int rndNum = (int) (Math.random() * 1001);
output.writeInt(rndNum);
System.out.println(rndNum);
}
output.close();
}
}
I'd recommend that you abandon DataInputStream and DataOutputStream.
Write the ints one to a line using FileWriter and read them using a BufferedReader, one per line. This is an easy problem.

CS106A handout 6 Exception java.lang.NullPointerException

Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}
I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}

Categories

Resources