How to format arrays in a different method? - java

How would I format my array as this? I've tried many different methods but I can't seem to get it to work.
I want it to return something like this
"Avg of 1 2 3 4 5 is 3.00"
public class AverageNumber {
private static int[] n = new int[5];
private static double total = 0;
public static void main(String[] a) {
AverageNumber object = new AverageNumber();
object.Dialogue();
}
private void Dialogue() {
int count = 1;
System.out.println("Skriv inn 5 tall" + count++);
for(int i=0; i<n.length; i++){
n[i] = Konsoll.readInt("Tall");
total = total + n[i];
}
double avg = total / n.length;
System.out.println("Avg of " + formatArray() + " is " + avg);
}
private static double formatArray() {
//Return all numbers
}
}

formatArray method should return String, like this :
private static String formatArray() {
String s = "";
for(int i = 0 ; i < n.length ; i++)
s+= String.valueOf(n[i])+" ";
return s;
}

Related

Array Index Out Of Bounds Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I have an array thats supposed to be a size of 3 which takes in 3 dive totals. It takes in an array of 7 scores from a double []. I have used a test scenario to see if the diveScore() method works and the calculations are correct. But when i try to read the numbers from a file and put them into an array, the scoreArray that holds the calculated dive score for each dive fails to store the data. The scoreArray in my hard coded test case works fine. Here is the exception from the console when run. I have tried to look at the line where the error states but the test data that I commented out in the main file works fine with the 3 arrays of scores for each dive. What am I missing? Every for loop doesn't have <= in it like many articles have been shown to me by everyone.
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3
at Diver.diveScore(Diver.java:33)
at Main.readFile(Main.java:74)
at Main.main(Main.java:10)
Main File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Diver [] divers = new Diver[25];
int numDivers = readFile(divers);
System.out.println(numDivers);
/*Diver d = new Diver("Frank Stalteri", "Middlesex County College");
double [] scores = {6.2, 3.5, 8, 7.3, 6, 9.1, 4.8};
double [] scores2 = {7.4, 5.4, 8, 3.7, 2.5, 7.8, 4};
double [] scores3 = {4.6, 7.2, 7.3, 1.4, 3.6, 8, 4.7};
d.diveScore(1, scores, 2);
d.diveScore(2, scores2, 4);
d.diveScore(3, scores3, 3);
System.out.println(d.toString());
*/
}
public static int readFile(Diver [] divers) throws FileNotFoundException {
File f = new File("divers.dat");
Scanner kb = new Scanner(f);
Diver d;
int count = 0;
int diveNum = 1;
while (kb.hasNextLine()) {
String name = kb.nextLine();
String school = kb.nextLine();
String dive1 = kb.nextLine();
String dive2 = kb.nextLine();
String dive3 = kb.nextLine();
//String [] of size 8 (inlcudes the difficulty #)
String [] scores1 = dive1.split("\\s+");
String [] scores2 = dive2.split("\\s+");
String [] scores3 = dive3.split("\\s+");
//gets the difficulty from String [] then parses
double diff1 = Double.parseDouble(scores1[scores1.length - 1]);
double diff2 = Double.parseDouble(scores2[scores2.length - 1]);
double diff3 = Double.parseDouble(scores3[scores3.length - 1]);
//make new double [] of size 7
double [] scores1D = new double[scores1.length - 1];
double [] scores2D = new double[scores2.length - 1];
double [] scores3D = new double[scores3.length - 1];
//loops through String [] and casts numbers without difficulty number
for (int i = 0; i < scores1D.length; i++) {
scores1D[i] = Double.parseDouble(scores1[i]);
//System.out.println(scores1D[i]);
}
for (int i = 0; i < scores2D.length; i++) {
scores2D[i] = Double.parseDouble(scores2[i]);
//System.out.println(scores2D[i]);
}
for (int i = 0; i < scores3D.length; i++) {
scores3D[i] = Double.parseDouble(scores3[i]);
//System.out.println(scores3D[i]);
}
d = new Diver(name, school);
divers[count] = d;
count++;
d.diveScore(diveNum, scores1D, diff1);
diveNum++;
d.diveScore(diveNum, scores2D, diff2);
diveNum++;
d.diveScore(diveNum, scores3D, diff3);
//System.out.println(d.toString());
}
kb.close();
return count;
}
public static void printDivers(Diver [] divers, int numDivers) {
System.out.println("All Divers\n");
for (int i = 0; i < divers.length; i++) {
if (divers[i] != null) {
System.out.println(divers[i]);
}
}
}
}
Diver File:
public class Diver {
private String name;
private String school;
private double [] scoreArray = new double [3];
private double totalScore;
Diver() {
}
Diver(String name, String school) {
this.name = name;
this.school = school;
}
//loop through score array and calculate the total score for each dive attempt
public double [] diveScore(int diveNum, double [] scores, double difficulty) {
double min = min(scores);
double max = max(scores);
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
total -= max;
total -= min;
total *= difficulty;
scoreArray[diveNum - 1] = Math.round(total * 100.0) / 100.0;
return scoreArray;
}
//finds smallest score in array of scores
private double min(double [] scores) {
java.util.Arrays.parallelSort(scores);
double min = scores[0];
return min;
}
//finds largest score in array of scores
private double max(double [] scores) {
java.util.Arrays.parallelSort(scores);
double max = scores[scores.length - 1];
return max;
}
//calculates total of the 3 dives
public double totalScore() {
for (int i = 0; i < scoreArray.length; i++) {
totalScore += scoreArray[i];
}
return totalScore;
}
public String toString() {
String str = name + ", " + school + ": " + totalScore() + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
return str;
}
public boolean equals(Diver d) {
boolean value = true;
if (d == null || !(d instanceof Diver)) {
value = false;
return value;
}
Diver diver = (Diver) d;
if (this.totalScore == d.totalScore) {
value = true;
return value;
}
return value;
}
}
Your first diver must start at 0
Main > readFile > while loop
int diveNum = 0;

How to print, sort and get temps above 90

Place code to print elements from arr_param
Place code to sort elements in arr_param in ascending order of fahrenheit temperature
Place code to print out elements from arr_param with temperatures > 90 deg. F
There is a private class to do the conversions from F to C to K.
public class Temperature {
public Temperature(double p_fahren) {
fahrenTemp = p_fahren;
}
public void setFahrenheit(double p_fahren) {
fahrenTemp = p_fahren;
}
public double getFahrenheit() {
return fahrenTemp;
}
public double getCelsius() {
double celsius_temp;
celsius_temp = (5.0 / 9.0) * (fahrenTemp - 32.0);
return celsius_temp;
}
public double getKelvin() {
double kelvin_temp = ((5.0 / 9.0) * (fahrenTemp - 32.0)) + 273.0;
return kelvin_temp;
}
public String toString() {
String ret_val = "";
ret_val = String.format("%.1f F, %.1f C, %.1f K",fahrenTemp, getCelsius(), getKelvin());
return ret_val;
}
}
We are not allowed to use the Arrays Util
public class Asn5_Test_Temperature
{
public static void main(String args[])
{
Temperature arr_temps [] =
{
new Temperature(90), new Temperature(75), new Temperature(65), new Temperature(95),
new Temperature(89), new Temperature(67), new Temperature(77), new Temperature(71),
new Temperature(55), new Temperature(65), new Temperature(64), new Temperature(74),
new Temperature(91), new Temperature(86), new Temperature(78), new Temperature(73),
new Temperature(68), new Temperature(94), new Temperature(91), new Temperature(62)
};
print_array("After population", arr_temps);
sort_array(arr_temps);
print_array("After sort", arr_temps);
print_days_above_90(arr_temps);
}
public static void print_array(String message, Temperature arr_param[])
{
System.out.println("----" + message + "---");
for(Temperature oneElem : arr_param)
System.out.print(oneElem + "\t");
System.out.println();
}
public static void sort_array(Temperature arr_param[])
{
int min;
int temp = 0;
for(int i = 0; i < arr_param.length; i++)
{
min = i;
for(int j = i + 1; j < arr_param.length; j++)
{
if(arr_param[j] < arr_param[min])
{
min = j;
}
}
temp = arr_param[i];
arr_param[i] = arr_param[min];
arr_param[min] = temp;
}
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i] + " ");
}
}
public static void print_days_above_90(Temperature arr_param[])
{
System.out.println("----Days over 90 F---");
for(int i = 0; i > 90; i++)
{
System.out.print(arr_param[i] + " ");
}
}
}
The program is supposed to print out the array, then in ascending order, then only the ones that are above 90 degrees F
I am having issue getting the sort code to work and getting it to sort the temperatures over 90 degrees F. I get three errors in my code: error: bad operand types for binary operator '<' and error: incompatible types: Temperature cannot be converted to int and error: incompatible types: int cannot be converted to Temperature
For this section call the getFahrenheit method to compare:
if(arr_param[j].getFahrenheit() < arr_param[min].getFahrenheit())
{
min = j;
}
For this section.. use the toString method. The purpose of the toString method is to convert your object data to a readable String.
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i].toString() + " ");
}
I hope this helps and let me know if you have any questions.

Create a Matrix from an ArrayList

I want to create a class that creates a Matrix via an ArrayList.
So that's what I did:
public class Matrice implements IMatrice {
ArrayList elements;
private int numLignes;
private int numColonnes;
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
public Matrice (int numLignes, int numColonnes, double valeur){
this.numLignes = numLignes;
this.numColonnes = numColonnes;
elements = new ArrayList(numLignes * numColonnes);
for(int i = 0; i < numLignes * numColonnes; i++){
elements.add(i, valeur);
}
}
}
Now that i created this, I wanted to try if it works. Then I created this toString() method:
public String toString() {
final DecimalFormat DEC_FORMAT = new DecimalFormat("0.0");
final int ESP = 8;
int num;
String sTmp;
String s = "[";
for (int i = 0 ; i < (numLignes * numColonnes) ; i++) {
//etendre i sur ESP colonnes
sTmp = "";
num = ESP - DEC_FORMAT.format(elements.get(i)).length();
for (int j = 0 ; j < num ; j++) {
sTmp = sTmp + " ";
}
sTmp = sTmp + DEC_FORMAT.format(elements.get(i));
if (i != 0 && i % numColonnes == 0) {
s = s + " ]\n[" + sTmp;
} else {
s = s + sTmp;
}
}
s = s + " ]";
return s;
}
Then this is my main to try the Matrix:
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
and i don't know why but i only get this :
[ ]
I know that a little thing is wrong but I can't find what. Could you help me?
Okay, i messed up...
The problem was in here :
elements.add(i, valeur);
i did a mistake... i mingled with the set() method.
here is the correction :
elements.add(valeur);

Sorting arrays from a file and printing results

I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.

Convert Hex value to ASCII character from array and how to eliminate null value?

I'm in the middle trying to convert the hex value that I retrieved from my method, compareHexaRGB to ASCII character which I want to know what output is going to produce. I don't know if I'm doing it wrong or I missed to code somewhere.
Code for extractMessage() method to convert hex value to ASCII:
public class extractMessage
{
private static String[][] char1;
private static String[][] char2;
private static String[][] in;
private static String[][] combine;
public static void extractMessage(String[][] inn, String[][] comb)
{
in = inn;
combine = comb;
}
public static void printString2DArray(String[][] in)
{
for (int i = 0; i < in.length; i++)
{
for(int j = 0; j < in[i].length; j++)
{
System.out.println(in[i][j] + " ");
}
System.out.println();
}
}
public static void charExtract()
{
compareHexaRGB hexRGB = new compareHexaRGB();
char1 = hexRGB.getCheck_hex2();
char2 = hexRGB.getCheck_hex4();
combine = new String[char1.length][char1[0].length];
for(int i = 0; i < char1.length; i++)
{
for(int j = 0; j < char1[i].length; j++)
{
//concatenate string
combine[i][j] = char1[i][j] + char2[i][j];
}
}
System.out.println("Char 1 + Char 2: ");
printString2DArray(combine);
}
public static String convertHexToString()
{
extractMessage em = new extractMessage();
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
String out = em.charExtract(); //error stated incompatible types: void cannot be converted to String
int decimal;
for(int i = 0; i < out.length(); i += 2)
{
String output = out.substring(i, (i + 2));
decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Output: " + temp.toString());
return sb.toString();
}
}
Second, I still cannot eliminate the NULL value from the retrieved value. Someone said I need to add a place to hold the characters which in this case the NULL value. I've done that but when I try to run the code then, here we go again, the nullpointerexception occur. I'm still new to java and lack of experience handling with java arrays and advanced java but I'm eager to learn. Java is very interesting language and I hope one day I could master on this language.
Code for compareHexaRGB() :
public class compareHexaRGB
{
private static int w;
private static int h;
private static BufferedImage img;
private static BufferedImage img2;
private static String[][] check_hex2;
private static String[][] check_hex4;
private static String[][] not_stega2;
private static String[][] not_stega4;
public static void compareHexaRGB(BufferedImage image, BufferedImage image2, int width, int height) throws IOException
{
w = width;
h = height;
img = image;
img2 = image2;
}
public void check() throws IOException
{
getPixelRGB1 pixel = new getPixelRGB1();
getPixelData1 newPD = new getPixelData1();
int[] rgb;
int count = 0;
int[][] pixelData = new int[w * h][3];
check_hex2 = new String[w][h];
check_hex4 = new String[w][h];
for(int i = 0; i < w; i++)
{
for(int j = 0; j < h; j++)
{
rgb = newPD.getPixelData(img, i, j);
for(int k = 0; k < rgb.length; k++)
{
pixelData[count][k] = rgb[k];
}
if(pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]))
{
System.out.println("\nPixel values at position 2 are the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j]);
not_stega2[i][j] = pixel.display_img2Hex2()[i][j]; // i've done the same as check_hex2 and check_hex4 method but why the error still occur?
}
if(pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]))
{
System.out.println("\nPixel values at position 4 are the same." + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
not_stega4[i][j] = pixel.display_img2Hex4()[i][j];
}
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]))
{
System.out.println("\nPixel values at position 2 are not the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j]);
check_hex2[i][j] = pixel.display_img2Hex2()[i][j];
System.out.println("\nOutput Hex 2: " + check_hex2[i][j]);
}
if(!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]))
{
System.out.println("\nPixel values at position 4 are not the same." + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
check_hex4[i][j] = pixel.display_img2Hex4()[i][j];
System.out.println("\nOutput Hex 4: " + check_hex4[i][j]);
}
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]) || (!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j])))
{
System.out.println("\nOne of the pixel values at position 2 and 4 are not the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j] + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]) || (pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j])))
{
check_hex2[i][j] = pixel.display_img2Hex2()[i][j];
System.out.println("\nOutput Hex 2: " + check_hex2[i][j]);
}
if(!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]) || (pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j])))
{
check_hex4[i][j] = pixel.display_img2Hex4()[i][j];
System.out.println("\nOutput Hex 4: " + check_hex4[i][j]);
}
}
count++;
System.out.println("\nOutput Count: " + count);
}
}
}
public String[][] getCheck_hex2()
{
return check_hex2;
}
public String[][] getCheck_hex4()
{
return check_hex4;
}
public String[][] getCheck_notStega2()
{
return not_stega2;
}
public String[][] getCheck_notStega4()
{
return not_stega4;
}
}
Hoping to eliminate these problems fast. Appreciate any help!
As i see there are 2 flaws in your code::
1. If charExtract() method is static then you need to access it in a static way as::
String out = extractMessage.charExtract();
2. Secondly as you are storing the value from charExtract() to a String variable "out"
so you need to return a string from the charExtract() method ,Declare it as
public static String charExtract()
{ ...
}
and return some value from charExtract like:
return combine[o][1];
public static void charExtract()
{ ...
}
and
String out = em.charExtract(); //error stated incompatible types
obviously don't match. Besides, why are you trying to call the static method charExtract() upon the instance em?
What do you store in those String[][] arrays?
char1 = hexRGB.getCheck_hex2();
char2 = hexRGB.getCheck_hex4();
Without knowing what they are supposed to contain, we cannot help you convert their content to anything.
At the moment I assume that you don't really want to deal with "hex" numbers; calculations are much easier performed on ints than on any String representation of numbers.

Categories

Resources