Random Array Sorting - arrays

Is it possible to sort (ascending) the randomly generated integer array for the following code? If, so how?
import java.util.Random;
public class RandomArraySorter {
public static void main(String args[]){
Random random = new Random();
int array[] = new int[10];
//number of integer spaces within the array:
for(int i = 0; i < 10; i++){
//random numbers from 1 to 100:
array[i] = random.nextInt(100) + 1;
System.out.print(array[i] + " ");
}
} //end of main
} //end of class

You can sort with:
Arrays.sort(array);

Related

Passing arrays between methods, and accessing them accordingly

I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);

How do I calculate median from an array from a different class?

I have an array of values in a different class. I am trying to calculate max, min and median from this array. I have my methods created but all values still display "0" when I run the program. Can someone please point out what I am doing wrong?
import java.util.*;
public class SortedListStats
{
public int maxTemp;
public int minTemp;
public int medianTemp;
public SortedListStats()
{
this.maxTemp = maxTemp;
this.minTemp = minTemp;
this.medianTemp = medianTemp;
InputOutput io = new InputOutput(); //This is my other class that has the array.
}
public int maxTemp(int[] io) //method to determine maximum temperature
{
int max = io[0];
for(int i = 0; i < io.length; i++)
{
if(max < io[i])
max = io[i];
}//end for statement
return max;
}//end method maxTemp
public int minTemp(int[] io) //method to determine mininum temperature
{
int min = io[0];
for(int i = 0; i < io.length; i++)
{
if(min > io[i])
min = io[i];
}//end for statement
return min;
}//end class minTemp
public int medianTemp(int[] io)
{
Arrays.sort(io);
int sum = 0;
int count = 0;
int median;
for(int i = 0; i > io.length; i++)
{
sum = sum + io[i];
count++;
}
median = sum/count;
return median;
}//end method medianTemp
}//end class SortedListStats
What code are you using to call the methods on this class? The first three lines of the constructor don't do anything. If you're expecting them to call your calculation methods, then they need to be after "new InputOutput()" and they need to be function calls. Like:
this.maxTemp = maxTemp(io.getValues());
You should refrain from naming your functions the same as your member variables to avoid confusion. For instance, the "maxTemp()" function could be "calculateMaxTemp()" instead.

How can I put an array into a method?

I have to find the LCM of two integers using the prime factors method and function calls.
I'm up to making a function to find the prime factorization of the first number, but I'm getting errors at int x = first_number; and with System.out.print(primeFactorization).
This is my code so far:
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int first_number;
int second_number;
System.out.print("Enter an integer: ");
first_number = reader.nextInt();
System.out.print("Enter another integer: ");
second_number = reader.nextInt();
}
public static int primeFactorization(int[] pfArray) {
int counter = 0;
pfArray = new int[10]; //created array in memory
int x = first_number;
for(int i=2;i<=x;i++){
while(x%i==0){
x=x/i;
pfArray[counter] = i;
++counter;
}
}
for(int i=0;i<counter;i++){
System.out.println(pfArray[i]);
}
}
System.out.println(primeFactorization);
}
I am just starting to learn Java, so please answer in very basic terms!
Thanks so much!
The variable first_number is declared in the first method and so cannot be used within the second method unless you pass it in as a parameter.
The only thing called primeFactorisation is the method. System.out.println requires an object (a variable) as its input. So you can't do it like that.

datatypes and arrays in java

Thoroughly confused on how to do this. What I want to do is to place the city with the lowest min, or max in the output. My understanding is you cannot throw a string in with another datatype in a method. How in the world can I match the name with the lowest temperature?
Lets say I want 3 cities:
I want to make the array 3 then:
Then I will add in the following cities, (Alanta, New York, Richmond)
The cities temperatures are (42.2, 98.8, -12.4)
Min is -12.4
Max is 98.8
That I have, how do I link Richmond's String that is stored in array[2] to temperature's double that is stored in array[2]? Any help is much appreciated.
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.lang.Math;
public class Ex9
{
public static void main(String[] args)
{
String message ="";
double min = 0, max = 0, avg = 0;
int counter = 1;
int numberOfCities = Integer.parseInt(JOptionPane.showInputDialog(null, "How many cities would you like to enter?"));
String[] nameOfCities = new String[numberOfCities];
double[] temperatureOfCities = new double[numberOfCities];
for (int i = 0; i < nameOfCities.length; i++)
{
nameOfCities[i] = JOptionPane.showInputDialog(null, "Please enter the name of city " +counter+" :");
temperatureOfCities[i] = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the current temperature of the city " + counter +" :"));
message += "City name " + nameOfCities[i] + ".\n"
+ "Temperature of city " + temperatureOfCities[i] + " is degrees\n";
counter++;
}//end numberOfCities loop
if(
JOptionPane.showMessageDialog(null, message + "\nThe average temperature is " +findAvg(temperatureOfCities)+ "\n[Name of city] has the lowest temperature, which is " + findMin(temperatureOfCities) + "\n[Name of city] has the highest temperature, which is " + findMax(temperatureOfCities));
}//end main
public static double findAvg(double[] temperatureOfCities)
{
double sum =0;
for(int i=0;i<temperatureOfCities.length;i++)
{
sum += temperatureOfCities[i];
}
sum = sum/temperatureOfCities.length;
return sum;
}//end findAvg
public static double findMin(double[] temperatureOfCities)
{
double min=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] <= temperatureOfCities[0])
{
min = temperatureOfCities[i];
}
}//end for loop
return min;
}//end findMin
public static double findMax(double[] temperatureOfCities)
{
double max=0;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
max = temperatureOfCities[i];
}
}//end for loop
return max;
}//end findMax
}//end program
Two main approaches here:
1) The procedural approach - just pass both arrays around instead of just one array. If they're kept synchronized there's no problem - just use the same index for both.
2) The object oriented approach - Define a class TemperatureReading with double temperature and string cityName. Then you can make a TemperatureReading[] array and pass it around, and the data is naturally associated.
Change your findMin, findAvg, and findMax methods to return a composite Measurement object.
class Measurement {
final double temperature;
final String cityName;
Measurment(String cityName, double temperature)
{
this.temperature = temperature;
this.cityName = cityName;
}
}
The updated methods could look something like this:
public static Measurement findMax(String[] nameOfCities, double[] temperatureOfCities) {
double maxTemp=0;
String maxName=null;
for(int i =0; i <temperatureOfCities.length;i++)
{
if (temperatureOfCities[i] >= temperatureOfCities[0])
{
maxTemp = temperatureOfCities[i];
maxName = nameOfCities[i];
}
} //end for loop
return new Measurement(maxTemp, maxName);
}
Now you can use the results like this:
Measurement maxMeasurement = findMax(nameOfCities, temperatureOfCities);
System.out.println(maxMeasurement.cityName + "has a temperature of " + maxMeasurement.temperature);
Similar goes for findMin and findAvg.

NPC movement in the array

I am doing a an array game, below is my Board class, which paints the array and spawns 5 hunters at 11,11, my 'route1' method should be the one to move hunters around whenever the player moves, however my hunter.x and hunter.y stay 11 after each re-paint, how do I fix this?
public class Board {
public String emptyfield = "-";
public String [][]a2 = new String[12][12];
public Hunter hunters[] = new Hunter[5];
public void paint(){
int numHunters =5 ;
for (int i =0; i < numHunters; i ++){
hunters[i] = new Hunter(11,11,"H");
}
Player player = new Player();
for (int r = 0 ; r < a2.length; r++){
for (int c= 0; c <a2[r].length; c++){
a2 [r][c] = emptyfield;
a2[Player.x][Player.y] = Player.name;
for (int i = 0; i < numHunters; i++){
Hunter h = hunters[i];
a2[h.x][h.y]=h.name;
}
System.out.print(" "+a2[r][c]);
}
System.out.println("");
}
System.out.println(" Strength: "+Player.hp);System.out.println(" Score "+Player.score);
}
public void route1(){
Board board = new Board();
Hunter Hunter = new Hunter(11,11,"H");
Scanner in = new Scanner(System.in);
Random number = new Random(2);
int random = number.nextInt(2);
if(random ==1)
Hunter.x = Hunter.x -1;
else
Hunter.y = Hunter.y -1;
}
If I read this correctly, you are recreating all your hunters at position 11,11 each time you call paint.
public void paint(){
int numHunters =5 ;
for (int i =0; i < numHunters; i ++)
{
hunters[i] = new Hunter(11,11,"H");
}
This code is replacing your array of hunters each time paint is called, erasing any changes made later on in code. You need to move (new Hunter(11,11,"H") to somewhere that is only called once.

Resources