I need help to see what I'm doing wrong.
I'm trying to generate 10 random values in 3 columns, but so far I can only generate one.
private static void displayDifficultyScore(ArrayList<TestDive> alist, double[] dArray)
{
// Create a Random class
Random rand = new Random();
double[] diffScores = new double[10];
double[] diffArray = new double[3];
// Print next line
System.out.println();
// Loop for Difficulty Scores
for (int j = 0; j < diffScores.length; j++) {
diffScores[j] = 2.0 + rand.nextDouble() * 3.0;
System.out.printf("%-7.1f%n", diffScores[j]);
}
}
public static void main(String[] args)
{
double[] diffScores = new double[1];
ArrayList<TestDive> alist = new ArrayList<TestDive>();
for (int j = 0; j < diffScores.length; j++) {
displayDifficultyScore(alist, diffScores);
}
}
}
Currently it's only printing out in 1 column:
2.9
4.4
4.9
3.7
4.3
3.1
4.2
4.5
4.2
2.9
Output that I want to achieve:
2.9 3.0 2.2
4.4 3.4 4.7
4.9 2.5 3.0
3.7 4.7 3.3
4.3 4.4 3.8
3.1 3.0 4.9
4.2 2.1 2.9
4.5 5.0 2.2
4.2 4.8 3.6
2.9 2.6 3.1
You can try generating a 2D array (or matrix) first and then printing it
Something like this
public class Hello {
private static double[][] generateDifficultyScores(int matrixLength, int matrixWidth) {
// Create a Random class
Random rand = new Random();
double[][] diffScores = new double[matrixLength][matrixWidth];
// Loop for Difficulty Scores
for (int i = 0; i < matrixLength; i++) {
for (int j = 0; j < matrixWidth; j++) {
diffScores[i][j] = 2.0 + rand.nextDouble() * 3.0;
}
}
return diffScores;
}
public static void main(String[] args) {
// generate random difficulty scores (stores it in a 2D array or matrix of values)
double[][] diffScores = generateDifficultyScores(10, 3);
// print out each array in matrix (line by line)
for (int j = 0; j < diffScores.length; j++) {
// print each element of the array separated by a tab `\t` and formatted to one decimal point
System.out.printf("%7.1f\t%7.1f\t%7.1f", diffScores[j][0], diffScores[j][1], diffScores[j][2]);
// add a newline for next iteration
System.out.println();
}
}
}
Related
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
class TestDive
{
private static void displayDifficultyScore(ArrayList<TestDive> alist, double[] dArray)
{
// Create a Random class
Random rand = new Random();
double[] difficulty = new double[5];
for (int i = 0; i < difficulty.length; i++) {
difficulty[i] = 2.0 + rand.nextDouble() * 3.0;
}
for (int i = 0; i < difficulty.length; i++) {
System.out.printf("D %-5d", i+1, difficulty[i]);
System.out.printf("%-5.1f", difficulty[i]);
}
}
public static void main(String[] args)
{
double[] difficulty = new double[1];
ArrayList<TestDive> alist = new ArrayList<TestDive>();
for (int i = 0; i < difficulty.length; i++) {
displayDifficultyScore(alist, difficulty);
}
}
}
This is my current code above. And my current output is this:
D 1 4.5 D 2 4.3 D 3 2.9 D 4 2.5 D 5 4.4
But I want it to look like this:
D 1 D 2 D 3 D 4 D 5
4.5 4.3 2.9 2.5 4.4
Just to mention that I am randomly generating these score values & I'm also making use of Array List to freely print how many D (no.) I want.
Let's say I have five int variables that are prompted for user input. User keys in the five value and two of those values are 0. I would like to ONLY print out values that are greater than zero.
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
I would like to write a dynamic print statement that would exclude the int variables with Zero value.
Currently, my print statement displays all values:
System.out.printf("%s %d%n%s %d%n%s %d%n%s %d%n%s %d%n","V1;","v1","V2:","v2","V3:","v3","V4:","v4","V5:","v5");
I tried writing if-else statements but that became very cumbersome.
Create a new method printNonZeroVars(Integer... ints).
public static void main(String[] args) {
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
printNonZeroVars(v1, v2, v3, v4, v5)
}
public void printNonZeroVars(int... ints) {
for (int i = 0; i < ints.length; i++) {
if (ints[i] > 0) {
System.out.printf("V%d%d%n", i, ints[i]);
}
}
}
I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.
So a simple way of achieving this would be to use some sort of Array/List.
ArrayList<Integer> list = new ArrayList<Integer>()
// Or as pointed out by David a better way would be to declare the list as
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
....
Once you have the list you can use a loop to loop through the list and do relevant checks - something like this
String str = "";
for(int i=0; i<list.size(); i++) {
if(list.get(i) == 0) {
continue;
}
str += "v"+i + ":" + Integer.toString(list.get(i));
}
System.out.println(str);
Its pseudo but should give you a good head start :)
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
Main Class:
public class Main {
private static String [] Countries={"UK", "Italy",
"Germany", "Thailand","Denmark"};
static double average[] = new double[5];
double[] results = new double[5];
public static String getWinner(ArrayList<MissUniverse>alist){
int champion = 0;
for (int s = 0; s < alist.size(); s++){
if (alist.get(s).average() > alist.get(0).average() ) {
winner= s;
}
}
return alist.get(winner).getCountry();
}
public static String firstRunnerUp(ArrayList<MissUniverse>alist){
int firstrunnerUp =0;
for (int s = 0; s < alist.size(); s++){
if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
firstrunnerUp = s;
}
}
return alist.get(firstrunnerUp).getCountry();
}
public static void main (String[] args){
ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
MissUniverse missUniverse[] = new MissUniverse[Countries.length];
for(int i=0;i<Countries.length;i++)
{
missUniverse[i] = new MissUniverse(Countries[i]);
missUniverse[i].getScore();
alist.add(missUniverse[i]);
}
System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-10s",
"Countries","1","2","3","4","5","Average");
System.out.println();
for (int i = 0; i < Countries.length; i++){
System.out.print(Countries[i]);
System.out.print(" ");
missUniverse[i].printInfo();
System.out.printf("%5.1f", alist.get(i).average() ); ///this line
System.out.println();
}
System.out.println("The result is");
System.out.println("Winner: Miss " + getWinner(alist) );
System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );
}
}
MissUniverse class:
class MissUniverse {
public static int SIZE=5;
private String country;
private double[] score;
public MissUniverse(String country){
this.country = country;
score = new double [SIZE];
}
public String getCountry(){
return country;
}
public void getScore(){
for (int i=0;i<score.length;i++)
{
score[i] = Math.random()*10;
}
}
public void setCountry(String newCountry) {
this.country = newCountry;
}
private int highest(){
int i;
double highest;
highest = score[0];
for (i = 0; i <score.length; i++)
{
if (highest < score [i])
{
highest = score[i] ;
}
}
return i;
}
private int lowest(){
int i;
double lowest;
lowest = score[0];
for (i = 0; i <score.length; i++)
{
if (lowest > score [i])
{
lowest = score[i];
}
}
return i;
}
public double average(){
double sum = 0.0;
for (int i = 0; i < score.length; i++){
sum += score[i];
}
double average;
average = (sum - score[lowest()] - score[highest()] )/ score.length -2;
}
public void printInfo(){
for(int i=0;i< score.length;i++){
System.out.printf("%-5.1f",score[i]);
}
}
}
The error:
Countries 1 2 3 4 5 Average
UK 3.3 5.8 6.6 4.8 0.2 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at MissUniverse.average(Main.java:121)
at Main.main(Main.java:50)
I think the problem is in the average() or lowest() or highest() methods but I cant find the bug. I dont think there is anything wrong in those methods that can lead to counting outside the array length (length is 8) and index is 0-7. I've looked at other links in stackoverflow but I can't find whats wrong. I hope someone can help me?
The output I am trying to achieve is:
Countries 1 2 3 4 5 Average
UK 6.2 2.5 9.7 4.3 0.1 3.4
Italy 7.1 1.2 1.6 5.5 1.9 3.7
Germany 8.5 3.3 6.7 4.0 6.0 5.9
Thailand 5.3 8.5 1.5 10.0 2.7 4.1
Denmark 3.1 4.9 5.4 0.8 3.2 3.4
The result is:
Winner: Miss Germany
1st runner up: Miss Thailand
The problem is actually in your average method. This line:
average = (sum - score[lowest()] - score[highest()] )/ score.length -2;
Needs to be changed to:
average = (sum - lowest() - highest() )/ score.length -2;
Remember that all indices start at 0 in arrays.
You also forgot to return a value, so you need to put return average; at the end of the average method. Also, in your getWinner method, you need to declare the variable winner by putting int winner = 0; at the beginning of the getWinner method.
highest() also needs to be edited to return highest;, and lowest() needs to be edited to return lowest;. You will need to change those return types to double to make this work.
Recently I have written a java program that executes selection sort on an array, however, it does not seem to return the correct output. What am I doing wrong?
Wanted output: [2.0, 3.7, 6.2, 7.4, 8.1, 8.5, 9.9, 15.7]
Actual output: [7.4, 2.0, 3.7, 6.2, 8.1, 8.5, 9.9, 15.7]
Code explanation: The method findMax finds the index of the largest object in the array, and the method process utilizes the method findMax to find the index of the largest number and swap it with the last, second-to-last, third-to-last, and so on term in order to put the array in order.
My code:
import java.util.Arrays;
import java.io.*;
public class Driver01
{
public static void main(String[] args)
{
//input
double[] myArray = {2.0, 3.7, 9.9, 8.1, 8.5, 7.4, 15.7, 6.2};
//sort the array
double[] sorted = process(myArray);
//output
System.out.println(Arrays.toString(sorted));
}
private static int findMax( int EndIndex, double[] enterArray) {
double max = 0;
int trueIndex = 0;
for( int x = 0; x < EndIndex; x++) {
if(enterArray[x] > max) {
max = enterArray[x];
trueIndex = x;
}
}
return trueIndex;
}
private static void swap(int swap1, int swap2, double[] enterArray) {
double temp = 0;
temp = enterArray[swap1];
enterArray[swap1] = enterArray[swap2];
enterArray[swap2] = temp;
}
private static double[] process(double[] enterArray) {
int range = enterArray.length -1;
for( int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range, enterArray);
range = range -1;
}
return enterArray;
}
}
When you call:
int j = findMax(range, enterArray);
in process(), range is defined as
int range = enterArray.length-1
So your findMax() function is not going through the entire array
You can fix this by changing your for loop in findMax() function to:
for (int x = 0; x < EndIndex+1; x++) {
...
}
There is probably a more elegant solution, but that is the problem in your code
EDIT:
A better solution would be to change your process() function to:
private static double[] process(double[] enterArray) {
int range = enterArray.length;
System.out.println("Array Length: " + enterArray.length);
for (int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range-1, enterArray);
range--;
}
return enterArray;
}
This way, findMax() is able to cycle through the full range of the array and swap is able to access the last element of the array. range is decremented since the max number is now the last element of the array. This is easier to understand from an outside perspective than my original answer.
I wrote the code, but there is no conversion from double to int.
public class Array {
public static void main(String[] args) {
int i;
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = int(Math.random() * 100);
System.out.print(ar1[i] + " ");
}
}
}
How can it be corrected?
ar1[i] = (int)(Math.random() * 100);
Conversion in Java looks like cast in C.
It should be like
ar1[i] = (int)(Math.random() * 100);
When you cast, cast type should be in brackets e.g. (cast type)value
Try this:
package studing;
public class Array {
public static void main(String[] args) {
Random r = new Random();
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = r.nextInt(100);
System.out.print(ar1[i] + " ");
}
}
}
Why?
Using Math.random() can return 1, this means Math.random()*100 can return 100, but OP asked for maximum 99! Using nextInt(100) is exclusive 100, it can only return values from 0 to 99.
Math.random() can not return -0.000001 that would be round to 0 and 1.0000001 can not be returned that should round to 1. So you have less chance to get 0 or 99 than all the numbers between. This way it is not realy random, to guess "its not 0 or 99" is more true than "its not 1 or 98".
Also it do not make a detour via casting and mathematic operations you don't realy need, hey you dont need to strictfp on amd-cpus or old intel-cpus.
This is not actually using the java.lang.Math class, but in Java 8 a random array can also be created in this fashion:
int[] random = new Random().ints(100, 0, 100).toArray();
My solution uses Random class instead of Math.random. Here it is.
private static int[] generateArray(int min, int max) { // generate a random size array with random numbers
Random rd = new Random(); // random class will be used
int randomSize = min + rd.nextInt(max); // first decide the array size (randomly, of course)
System.out.println("Random array size: " + randomSize);
int[] array = new int[randomSize]; // create an array of that size
for (int i = 0; i < randomSize; i++) { // iterate over the created array
array[i] = min + rd.nextInt(max); // fill the cells randomly
}
return array;
}