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();
}
}
}
Related
I have a problem how to find GCD and LCM using ArrayList. Now I have implemented Euklides algorithm using primitive type. Below are my model and view packages. Please give me advice how change method in the model?
Model:
package Model;
import java.util.ArrayList;
import java.util.List;
/**
*
* Class used to calculate two math formulas.
*
* #author anonymous
* #version 1.24
*
*/
public class LeastGreatestCommon {
int result; // result of counting Least Common Multiple **
int result2; // result of counting Greatest Common Divisor **
/**
* Method counting Greatest Common Divisor from Euclidean algorithm
*
* #param a the first value of arguments
* #param b the second value of arguments
* #return returns the value of the largest common divisor for two input
* values
* #throws NegativeValueException where is one or more negative values
*/
public int gcd(int a, int b) throws NegativeValueException {
if (a < 0) {
throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
}
return b == 0 ? a : gcd(b, a % b);
}
/**
* Method counting Least Common Multiple from Euclidean algorithm
*
* #param a the first value of arguments
* #param b the second value of arguments
* #return returns the value of the least common multiple for two input
* values
* #throws NegativeValueException where is one or more negative values
*/
private int lcm(int a, int b) throws NegativeValueException {
if (a < 0) {
throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
}
return a * b / (gcd(a, b));
}
/**
* Method counting Greatest Common Divisor of n numbers
*
* #param r the number of arguments that will be used to calculate GCD
* #param tab_tmp the value of the array
* #return returns the value of the Greatest common divisor for all input
* values from the input stream or defined arguments
* #throws NegativeValueException where is one or more negative values
*/
public int calculateGreatestCommonDivisor(int r, int number) throws NegativeValueException {
List<Integer> getGreatestCommonDivisor = new ArrayList<Integer>();
for (int i = 0 ; i < r ; ++i) {
getGreatestCommonDivisor.add(i);
result2 = gcd(result2, getGreatestCommonDivisor.get(i));
// getGreatestCommonDivisor.remove(i);
}
return result2;
}
/**
* Method counting Least Common Multiple of n numbers
*
* #param r the number of arguments that will be used to calculate LCM
* #param tab_tmp the value of the array
* #return returns the value of the Least Common Multiple for all input
* values from the input stream or defined arguments
* #throws NegativeValueException where is one or more negative values
*/
// public int calculateLeastCommonMultiple(int r, int[] tab_tmp) throws NegativeValueException {
//
// int i; // integer representing the i-element array
// int[] tab = tab_tmp; // element of the array **
// int r_tmp = r; // number of elements in the array **
// r = tab.length;
// result = lcm(tab[0], tab[1]);
//
// for (i = 1; i < r; i++) {
// if (tab[i] < 0) {
// throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
// }
// result = lcm(result, tab[i]);
// }
// return result;
// }
}
View:
package View;
import Model.LeastGreatestCommon;
import Model.NegativeValueException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Main view class
*
* #author anonymous
* #version 1.23
*
*/
public class View {
/**
* The main method of counting calculate based on the given arguments value
* of GCD and LCM
*
* #param args the command line arguments
*/
public static void main(String[] args) throws NegativeValueException {
int ResultOfTheMultiple;
int ResultOfTheDivisor;
//int r_tmp;
LeastGreatestCommon leastGreatestCommon = new LeastGreatestCommon(); // Creating new object of LeastGreatestCommon class
// Scanner scanner = new Scanner(System.in);
ArrayList<Integer> getGreatestCommonDivisor = new ArrayList<>();
if (args.length == 0) { // Interaction with the user via the console
int r;
int number = 0;
Scanner input = new Scanner(System.in); // Creating Scanner object class associated with the input stream of object
System.out.println("How many numbers will we count? ");
r = input.nextInt();
//int[] tab = new int[r];
//System.out.println(r);
for (int i = 0; i < r; i++) {
System.out.println("Enter the number ");
number = input.nextInt();
}
System.out.println("The array consists of " + r + " elements\n");
for (int i = 0; i < r ; ++i) {
System.out.print(number + " , ");
}
System.out.println("\n");
try {
// getGreatestCommonDivisor.forEach(s -> System.out.println(s));
ResultOfTheDivisor = leastGreatestCommon.calculateGreatestCommonDivisor(r, number);
// for (Integer calculations : ResultOfTheDivisor) {
// System.out.println(calculations);
// }
// ResultOfTheDivisor.forEach(System.out::println);
//ResultOfTheMultiple = leastGreatestCommon.calculateLeastCommonMultiple(r, tab);
System.out.println("The Greatest Common Divisor of these numbers is " + ResultOfTheDivisor);
// System.out.println("The Least Common Multiple of these numbers is " + ResultOfTheMultiple);
} catch (NegativeValueException ex) {
// System.out.println(e);
System.out.println(ex.getMessage());
}
}
// if (args.length > 1) { // Interaction with the user using arguments in the project properties
//
// System.out.println("Arguments were entered");
// System.out.println("\n");
// int[] tab_tmp = new int[args.length];
// r_tmp = Integer.parseInt(args[0]);
//
// for (int i = 0; i < args.length; i++) {
// tab_tmp[i] = Integer.parseInt(args[i]);
// }
//
// try {
// ResultOfTheDivisor = leastGreatestCommon.calculateGreatestCommonDivisor(r_tmp, tab_tmp);
// ResultOfTheMultiple = leastGreatestCommon.calculateLeastCommonMultiple(r_tmp, tab_tmp);
// System.out.println("The Greatest Common Divisor of these numbers is " + ResultOfTheDivisor);
// System.out.println("The Least Common Multiple of these numbers is " + ResultOfTheMultiple);
// } catch (NegativeValueException ex) {
// System.out.println(ex.getMessage());
// }
// }
}
};
The issue was caused because in the method CalculateGreatestCommonDivisor doesn't get any normal result. Can you check this one?
I am testing a program I wrote for an assignment, and right now it's testing at 50% against test cases. I get the following errors when I submit, but I can't figure out why. I tried changing some pieces of code and retesting, but no matter what I do I get the same errors, so I must be completely missing what I should be looking for. Here is the CSV file from which the data is being pulled -
CSV Data File. Here are the errors I get:
Here is my code:
Main class:
/*
* 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 csc212hw04;
import java.io.File;
import java.util.Scanner;
/**
*
* #author Michal
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception{
Scanner kb = new Scanner(System.in);
boolean flag = true;
System.out.println("Welcome to the Car Database");
System.out.println("Enter the size of the array:");
int size = Integer.parseInt(kb.nextLine());
CarDatabase db1 = new CarDatabase(size);
System.out.println("Enter the name of the input file:");
String userFile = new String(kb.nextLine());
db1.readFile(userFile);
while (flag) {
System.out.println("Enter make, mpg, weight, all, or quit:");
String command = kb.nextLine();
if (command.equals("make")) {
System.out.println("Enter the make:");
String make = kb.nextLine();
db1.displayMake(make);
} else if (command.equals("mpg")) {
System.out.println("Enter the mpg range:");
double mpgLow = Double.parseDouble(kb.nextLine());
double mpgHigh = Double.parseDouble(kb.nextLine());
db1.mpgRange(mpgLow, mpgHigh);
} else if (command.equals("weight")) {
System.out.println("Enter the weight range:");
double weightLow = Double.parseDouble(kb.next());
double weightHigh = Double.parseDouble(kb.next());
db1.weightRange(weightLow, weightHigh);
} else if (command.equals("all")) {
CarDatabase.displayAll();
} else if (command.equals("quit")) {
flag = false;
}
}
}
}
CarDatabase class:
/*
* 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 csc212hw04;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
* #author Michal
*/
public class CarDatabase {
private static Car[] database;
public CarDatabase(int s) {
this.database = new Car[s];
}
public boolean isFull() {
boolean full = true;
for (int i = 0; i < database.length; i++) {
if (database[i] == null) {
full = false;
}
}
return full;
}
public static void readFile(String f) throws FileNotFoundException {
File file = new File(f);
int lineNum = 0;
Scanner sc = new Scanner(file);
String csvSplitBy = ",";
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] carData = line.split(csvSplitBy);
String model = carData[0];
String make = carData[1];
double mpg = Double.parseDouble(carData[2]);
int weight = Integer.parseInt(carData[3]);
int year = Integer.parseInt(carData[4]);
database[lineNum] = new Car(model, make, mpg, weight, year);
lineNum++;
}
}
public static void displayMake(String m) {
for (int i = 0; i < database.length; i++) {
if (database[i].make.equals(m)) {
database[i].toString();
}
}
}
public static void mpgRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if (database[i].mpg >= l && database[i].mpg <= h) {
database[i].toString();
}
}
}
public static void weightRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if ((database[i].weight >= l) && (database[i].weight <= h)) {
database[i].toString();
}
}
}
public static void displayAll() {
for (int i = 0; i < database.length; i++) {
database[i].toString();
}
}
}
Car class:
/*
* 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 csc212hw04;
/**
*
* #author Michal
*/
public class Car {
public String model, make;
public double mpg;
public int weight, year;
public Car(String md, String mk, double umpg, int w, int y) {
model = md;
make = mk;
mpg = umpg;
weight = w;
year = y;
}
public String toString() {
return "Model:" + model + " Make:" + make + " mpg:" + " weight:" + " year:" + year;
}
}
Here is a sample from the CSV file if you cannot see it:
You are probably getting to the End of File and you try to split. The array then doesn't have any value. Make sure there is no blank line at the end of your database, or put a check in your readfile to make sure that if the carData.length == NUMBER OF DATA FIELDS
Update
You also should check to make sure that you don't pass the total number of database entries you have. So do:
while(sc.hasNextLine() && lineNum < database.length) {
ArrayIndexOutOfBoundsException is thrown in very specific circumstances:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
In your code, you assume that each row in your csv has the same number of fields.
You're also assuming that the size of database array matches the number of cars in your file. Since you don't create your database array entries until you read them from the file - but you pre-initialize the size database array, you could end up reading past the end of your database if the number of records in the CSV is larger than the value you initialize for the database size.
I have been working on this for quite some time and cannot figure out why i am getting the error
Exception in thread "main" java.lang.NullPointerException
at LifeGame.cellValue(LifeGame.java:91)
at Life.main(Life.java:31)
after I input the file name each time I run it.
This is the main file.
Life.java
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Life {
static PrintStream theScreen = new PrintStream(System.out);
static Scanner theKeyboard = new Scanner(System.in);
public static void main( String args[]) {
theScreen.print("\nEnter the name of the initial configuration file: ");
String inFile, str;
inFile = theKeyboard.nextLine();
// initialize the game
LifeGame theGame = new LifeGame(inFile);
int count = 0;
while(true)
{
// display current configuration
theScreen.println(theGame.cellValue(0, 0));
theScreen.println("\nGeneration " + count
+ " - press 'Enter' for the next "
+ "generation or type 'done' to finish");
str = theKeyboard.nextLine();
if (str.equals("done")) break;
// generate next configuration
theGame.nextGeneration();
count++;
}
}
}
This is LifeGame.java
import java.util.*; // Scanner
import java.io.*; // File
public class LifeGame
{
// define private variables here
int myRows=0;
int myCols=0;
int[][] myGrid;
static PrintStream theScreen = new PrintStream(System.out);
// ++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame constructor. *
// * Receive: fileName, a string. *
// * Precondition: fileName contains the name of *
// * a file containing a Life configuration *
// * (the number of rows, the number of columns, *
// * and the values of each cell). *
// * Postcondition: myGrid has been initialized *
// * to the configuration in fileName. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++
public LifeGame(String fileName)
{
Scanner theFile = null;
try
{
theFile = new Scanner(new File(fileName));
}
catch (FileNotFoundException e)
{
System.err.println("File Not Found");
System.exit(1);
}
myRows = theFile.nextInt();
myCols = theFile.nextInt();
int[][] myGrid = new int[myRows][myCols];
for (int i = 0; i < myRows; i++)
{
for (int j = 0; j < myCols; j++)
{
int num = theFile.nextInt();
myGrid[i][j] = num;
}
}
theFile.close();
System.out.println(myRows+" "+myCols);
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame columns extractor. *
// * Return: the number of columns in my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public int columns()
{
return myCols;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
// * LifeGame rows extractor. *
// * Return: the number of rows in my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
public int rows()
{
return myRows;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
// * LifeGame cell Value extractor. *
// * Return: the value in cell [row][col] *
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
public int cellValue(int row,int col)
{
for (int i = 0; i < rows(); i++)
{
for(int j = 0; j < columns(); j++)
{
if (myGrid[i][j] == '1')
{
theScreen.println("* ");
}
else
{
theScreen.println(" ");
}
}
System.out.println();
}
return 0;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * Mutator to generate next LifeGame generation. *
// * Postcondition: For each cell myGrid[r][c]: *
// * if myGrid[r][c] had 3 living neighbors: *
// * myGrid[r][c] contains a 1. *
// * if myGrid[r][c] had less than 2 neighbors OR *
// * myGrid[r][c] had more than 3 neighbors: *
// * myGrid[r][c] contains a 0. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public void nextGeneration()
{
int neighbors = 0;
int tempGrid[][] = myGrid;
for (int r = 0; r < myRows; r++)
{
for (int c = 0; c < myCols; c++)
{
neighbors = (tempGrid[r-1][c-1]
+ tempGrid[r-1][c]
+ tempGrid[r-1][c+1]
+ tempGrid[r][c-1]
+ tempGrid[r][c+1]
+ tempGrid[r+1][c-1]
+ tempGrid[r+1][c]
+ tempGrid[r+1][c+1]);
if ( neighbors == 3)
{
myGrid[r][c] = 1;
}
else if ( neighbors < 2 || neighbors > 3)
myGrid[r][c] = 0;
}
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame toString function member. *
// * override the toString method to display the array *
// * Return: a String containing my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public String toString()
{
return "";
}
} // end of the class
And this is the file being read in
test.life
5 5\n
0 0 0 0 0\n
0 0 1 0 0\n
0 0 1 0 0\n
0 0 1 0 0\n
0 0 0 0 0\n
The problem is myGrid is null. If you look at LifeGame() you will notice you're redefining a local version of myGrid so you're not setting the member variable correctly.
Change:
int[][] myGrid = new int[myRows][myCols];
To:
myGrid = new int[myRows][myCols];
MyGrid is probably null. You initialize something called myGrid in your constructor (scoped only in the constructor), but not self.myGrid (which is for the class)
Around line 40 in LifeGame.java you have:
int[][] myGrid = new int[myRows][myCols];
If you're trying to instantiate the instance variable myGrid instead of a local myGrid, then you should take off the int[][]
myGrid = new int[myRows][myCols];
Since you never instantiate the instance variable, it's null when you call it later in the cellValue() function.
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();
}
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