passing array values from methods and writing to text output file - java

So i have been slogging threw this project all day and at this point i have no idea where to go. The project is to create an array of 1000 random integers that are assigned values of 1-10. Next, create an array that stores the frequency of the integers generated. Next, calculate the average of the integers in an array. And finally, to output all those values to a text file. I have watched countless videos and am utterly lost at this point. the examples in the text are for one main method that outputs the text. I am not sure if i am supposed to put the text file commands into the main method or if i should develop a separate method to handle the text file output. If so, i am not sure if i pass the arrays from my other methods into a new textFile method or what have you...
Last week was my first time working with multiple methods and this week is my first work with arrays so any guidance here would be greatly appreciated.
This is my code so far.
package randomintegers;
import java.util.*;
import java.io.*;
public class RandomIntegers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int randomNumbers[] = new int [1000];
int i;
for (i=0;i<randomNumbers.length;++i){
randomNumbers[i] = 1 + (int)(Math.random() * 10);
}
calcFrequency(randomNumbers);
calcAverage(randomNumbers);
}
public static void calcFrequency(int[] inputArray){
int[] freq=new int[10];
int i;
for (i=0;i<inputArray.length;++i){
++freq[inputArray[i]-1];
}
//System.out.println(inputArray);
//System.out.println( (inputArray[i] + 1) + " occured " + freq[i] + " times" );
System.out.println(Arrays.toString(freq)); }
public static double calcAverage(int[] randomNumbers)
{
int sum = 0;
for(int i : randomNumbers) sum += i;
return ((int) sum)/randomNumbers.length;
}
public static void textRead(int[] calcAverage int[] calcFrequency)throws FileNotFoundException;{
Scanner input = new Scanner(new File("randomIntegers.txt"));
int frequency = input.nextInt();
int [] outputFreq = new int[10];
}
}

You can use PrintWriter to write to file.
I have commented code, so it will be easy for you to understand.
/**
* Writes array to file.
* #param array array to write
* #param fileName name of file in which array will be written
* #throws FileNotFoundException if creating file fails
*/
public void writeArrayToFile(int [] array, String fileName) throws FileNotFoundException{
// create PrintWriter object to write to file
PrintWriter writer = new PrintWriter(fileName);
// iterate through array, write each element of array to file
for(int i = 0; i < array.length; i++){
// write array element to file
writer.print(array[i]);
// write separator between array elements to file
writer.print("\n");
}
// done writing, close writer
writer.close();
}

Related

need assistance with writing random array values to a file in Java

I am struggling with a beginning Java class. I have to modify a program to replace a user-generated integer array with a Random() number generated double precision floating point array.
This is what I have so far. I think it is generating the correct dataset, but I can't get the PrintWriter section configured correctly.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assign6array;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Random;
/**
*
* #author matthew.neesley
*/
public class Assign6Array {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
int[] array = new int[10];
int count = 0;
int numbers = 0;
Random rd = new Random(); // creating Random object
double[] arr = new double[10];
for (int i = 0; i < array.length; i++) {
arr[i] = rd.nextInt(); // storing random integers in an array
while (numbers!= -1 && count <= 9)
{
array[count] = numbers;
count++;
System.out.println(arr[i]); // printing each array element
PrintWriter writer = new PrintWriter(System.out);
printr.print(arr[i]);
}
}
}
}
You are creating PrintWriter like this
PrintWriter writer = new PrintWriter(System.out);
The variable is named writer, but you use it like this:
printr.print(arr[i]);
Using printr variable which doesn't exist. Do simply:
writer.print(arr[i]);
Also, you need PrintStream acts as a buffer, so you will have to flush it's contents so that they are written to the output stream.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Random;
/**
* #author matthew.neesley
*/
public class Assign6Array {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
int[] array = new int[10];
int count = 0;
int numbers = 0;
Random rd = new Random(); // creating Random object
double[] arr = new double[10];
for (int i = 0; i < array.length; i++) {
arr[i] = rd.nextInt(); // storing random integers in an array
PrintWriter writer = new PrintWriter(System.out);
while (numbers != -1 && count <= 9) {
array[count] = numbers;
count++;
System.out.println("abc " + arr[i]); // printing each array element
writer.println(arr[i]);
writer.flush();
}
writer.close();
}
}
}

Getting 0.0 on NumberAnalyzer.java. Need helps

Write a class with a constructor that accepts a file name as its argument. Assume the file contains a series of numbers, each written on a separate line. The class should read the contents of the file into an array, and then displays the following data.
The lowest number in the array
The highest number in the array
The total of the numbers in the array
The average of the numbers in the array.
The file, Numbers.txt used for the above program contains these twelve numbers:
8.71
7.94
3.01
29.27
9.23
82.76
12.6
47.99
63.89
1.09
22.23
79.17
This is the main program: NumberAnalyzerDemo.java
import java.io.*; // Needed for IOException
/**
This program demonstrates a solution to the
Number Analysis Class programming challenge.
*/
public class NumberAnalyzerDemo
{
public static void main(String[] args) throws IOException
{
// Create a NumberAnalyzer object.
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
// Display data about the numbers in the file.
System.out.println("The lowest number in the file is " +
na.getLowest());
System.out.println("The highest number in the file is " +
na.getHighest());
System.out.println("The total of the numbers in the file is " +
na.getTotal());
System.out.println("The average of the numbers in the file is " +
na.getAverage());
}
}
This is the class: NumberAnalyzer.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
/**
The NumberAnalyzer class is to searching the numbers in a file.
*/
public class NumberAnalyzer
{
private double[] numbers;
private int count;
File file;
Scanner scan;
/**
Constructer that accepts the file name as its argument.
*/
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
}
/**
The getLowest() method to search the file and pull out the lowest
number in the file.
#return Return the lowest number.
*/
public double getLowest()
{
double low = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (low > numbers[i])
{
low = numbers[i];
}
}
return low;
}
/**
The getHighest() method to search the file and pull out the highest
number in the file.
#return Return the highest number.
*/
public double getHighest()
{
double high = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (high < numbers[i])
{
high = numbers[i];
}
}
return high;
}
/**
This method calculate the total of all the number in the file.
#return Adding all number in the file.
*/
public double getTotal()
{
double total = 0;
for (int i = 0; i < numbers.length; i++)
{
total += numbers[i];
}
return total;
}
/**
This method used to calculate the average of the numbers in the file.
#return Using the getTotal() divided to the length of the numbers.
*/
public double getAverage()
{
return getTotal() / numbers.length;
}
/**
This method to read all the file txt and get the right number.
*/
private void getNumbers(String filename)
{
while(scan.hasNext())
{
numbers[count] = scan.nextDouble();
count++;
}
scan.close();
}
/**
This method
*/
private int getNumberOfValues(String filename)
{
return count ;
}
}
I'm getting 0.0 for all the output. Please give me some suggestions. Thanks!
solution
change you method
private void getNumbers(String filename)
to
public void getNumbers()
and then do
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
na.getNumbers();
You're not calling your getNumbers() method, and so haven't populated your numbers[] array.
Just make the call in your constructor, like this:
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
getNumbers();
}
It looks like it doesn't need to have the String argument, so you could remove that, unless you're still planing to implement something with it.

Implementing object parameters in other classes

I'm hoping someone can help me with these two values that have me stuck on a project. I have two classes and this first one generates a 2D array with random values.
import java.util.concurrent.ThreadLocalRandom;
public class Guitar {
private int strings;
private int chords;
public Guitar(int mstrings, int mchords) {
this.strings = mstrings;
this.chords = mchords;
}
private double[][] song = new double[strings][chords];
public void generateSong() {
for (int i = 0; i < song.length; i++) {
for (int j = 0; j < song[i].length; j++) {
song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186);
System.out.printf(" %.2f",song[i][j]);
}
System.out.println();
}
}
}
The number of rows and columns is determined by command line arguments. args[0] is the number of rows, args[1] is the number of columns. I converted them to int variables in the main method class
public class Songwriter {
public static void main(String[] args) {
System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords.");
String args0 = args[0];
int strings = Integer.parseInt(args0);
String args1 = args[1];
int chords = Integer.parseInt(args1);
Guitar guitarObj1 = new Guitar(strings, chords);
guitarObj1.generateSong();
}
}
My problem lies in passing the int variables of the command line arguments to make the 2D array the corresponding size. I know my code isn't completely wrong b/c when I set the strings and chords variables equal to 3 and 4 or whatever in the Guitar class itself, the table prints fine.
Sorry if I seem clueless. My class just covered the first chapter on object oriented programming and I've yet to get the fundamentals down.
This is the problematic line:
private double[][] song = new double[strings][chords];
When you create a new object of your Guitar class, the song array is initialized with whatever the values of strings and chords are at that time, which would (most probably) be 0.
Change it to this:
private double[][] song;
public Guitar(int mstrings, int mchords) {
this.strings = mstrings;
this.chords = mchords;
song = new double[mstrings][mchords];
}
EDIT : OP you just answered your own question :)
It doesn't crash but the only output is the system.out.print in the
first line of the main. I believe it's because the strings and chords
variables default to 0, making the array 0x0, and I'm failing to
change their values

Program reads in the contents of a file into an array, and display both the console and write to a file

I am writing a program that prompts the user for a file name. I have to assume that the file contains an integer representing the number of n data values, followed by a series of n floating numbers(which was given to me in a file called RandomFloats), each written on a separate line. This program should read in the contents of the RandomFloats file into an array, and then both display in the console and write to a file the following data: the number of floating point numbers in the array, the lowest and highest number in the array, the total and the average. Here is my code so far(I will put in a comment at the part that is not working)
import java.io.File;
import java.util.*;
public class Problem9 {
/**
* #param args
*/
public static void main(String[] args) {
File rf = new File("RandomFloats");
Scanner kb = new Scanner(rf); //Unhandled exception type FileNotFoundException
double[] numFloats = new double [4268];
for (int i = 0; i < numFloats.length; i++){
numFloats[i] = kb.nextInt();
}
System.out.println("Please enter a file name");
String fileName = kb.nextLine();
minValue (numFloats);
maxValue (numFloats);
totalValue (numFloats);
averageValue (numFloats);
}
public static void minValue (double[] numFloats){
double min = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] < min){
min = numFloats[i];
}
}
System.out.println("Min Value: " + min);
}
public static void maxValue (double[] numFloats){
double max = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] > max){
max = numFloats[i];
}
}
System.out.println("Max Value: " + max);
}
public static void totalValue (double[] numFloats){
double total = 0;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
System.out.printf("\nTotal1: %.1f" , total);
}
public static void averageValue (double[] numFloats){
double total = 0;
double average;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
average = total / numFloats.length;
System.out.printf("\nAverage: %.1f" , average);
}
}
I am unsure how to print out the sample size and the file RandomFloats I created isnt being read into the array. Please help me I am completely stuck, Thanks!!
The exception FileNotFoundException indicates that the file you specified was not found. Perhaps it's not in the same directory that your program is executing in? Perhaps it has some sort of suffix like .txt? Try providing the fully qualified path to the file, like:
"/Users/bob.bobberton/RandomFloats"
Looks like your problem starts with the line
File rf = new File("RandomFloats");
You're not passing a valid path to the File constructor, which is why the next line
Scanner kb = new Scanner(rf);
is throwing a filenotfound exception
You should check out these links
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
when you try to read a file, you need to provide it's extension so it is recognized as a file not a directory ... this happened to me several times
File rf = new File("RandomFloats.whatEver");

Resolving ArrayIndexOutOfBoundException while using ArrayList

I am a beginner in java development field and still i am a learner of Java Programming. I wanted to see the output for the Support Vector Machine classifier on netbeans IDE. So i copied this attached piece of code and tried to run by using all the other required class and main method as well but i am getting Number format exception when i give a file containing input like 23,25,26,27 during the call of the method loadBinaryProblem() in main method and if i remove all the commas and replaced them with space ex: 23 25 26 27 then i am getting ArrayIndexOutOfBound exception instead of it. So anybody can help to get the output properly without any error.
package svmlearn;
import java.io.*;
import java.util.*;
/**
* Class representing an optimization problem (a data setting);
* taken from liblinear; "bias" excluded
* #author miafranc
*
*/
public class Problem {
/** The number of training data */
public int l;
/** The number of features (including the bias feature if bias >= 0) */
public int n;
/** Array containing the target values */
public int[] y;
/** Map of categories to allow various ID's to identify classes with. */
public CategoryMap<Integer> catmap;
/** Array of sparse feature nodes */
public FeatureNode[][] x;
public Problem() {
l = 0;
n = 0;
catmap = new CategoryMap<Integer>();
}
/**
* Loads a binary problem from file, i.e. having 2 classes.
* #param filename The filename containing the problem in LibSVM format.
*/
public void loadBinaryProblem(String filename) {
String row;
ArrayList<Integer> classes = new ArrayList<Integer>();
ArrayList<FeatureNode []> examples = new ArrayList<FeatureNode []>();
try {
BufferedReader r = new BufferedReader(new FileReader(filename));
while ((row = r.readLine()) != null) {
String [] elems = row.split(" ");
//Category:
Integer cat = Integer.parseInt(elems[0]);
catmap.addCategory(cat);
if (catmap.size() > 2) {
throw new IllegalArgumentException("only 2 classes allowed!");
}
classes.add(catmap.getNewCategoryOf(cat));
//Index/value pairs:
examples.add(parseRow(elems));
}
x = new FeatureNode[examples.size()][];
y = new int[examples.size()];
for (int i=0; i<examples.size(); i++) {
x[i] = examples.get(i);
y[i] = 2*classes.get(i)-1; //0,1 => -1,1
}
l = examples.size();
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Parses a row from a LibSVM format file.
* #param row The already split row on spaces.
* #return The corresponding FeatureNode.
*/
public FeatureNode [] parseRow(String [] row) {
FeatureNode [] example = new FeatureNode[row.length-1];
int maxindex = 0;
for (int i=1; i<row.length; i++) {
String [] iv = row[i].split(":");
int index = Integer.parseInt(iv[0]);
if (index <= maxindex) {
throw new IllegalArgumentException("indices must be in increasing order!");
}
maxindex = index;
double value = Double.parseDouble(iv[1]);
example[i-1] = new FeatureNode(index, value);
}
if (n < maxindex)
n = maxindex;
return example;
}
}
i guess NumberformatExceptions comes from:
String [] elems = row.split(" "); //nothing done by "23,25,26,27"
//Category:
Integer cat = Integer.parseInt(elems[0]); //you are trying to parse "23,25,26,27"
ArrayIndexOutOfBound comes from:
String [] iv = row[i].split(":");//nothing done
...
double value = Double.parseDouble(iv[1]);//1 is out of bound

Categories

Resources