getting max value in an array - java

simple question. I'm new to using arrays and multiple classes and could use some help. Basically, my program is supposed to sort the array in ascending order(done) and then output the max number. But I have to use two classes (client class and other) I always seem to have trouble bringing the code from one class and implementing it into another. I'm trying to implement my getMaxValue into the client class to output it. I'm sure I'm missing something simple or overlooking it. Any help or suggestions would be appreciated!
First Class:
public class Chapter8Number16{
public static void selectionSort(int[]array){
int temp;
int max;
int numbers[] = new int[0];
for(int i = 0; i< array.length;i++){
max=indexOfLargestElement(array, array.length-i);
temp=array[max];
array[max]=array[array.length-i-1];
array[array.length-i-1]=temp;
}
}
private static int indexOfLargestElement(int[]array,int size){
int index=0;
for(int i = 1; i<size;i++){
if (array[i]>array[index])
index=i;
}
return index;
}
public static int getMaxValue(int[] array){
int maxValue = array[0];
for(int i=1;i < array.length;i++){
if(array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
}
Client Class:
import java.util.Random;
public class Chapter8Number16Client {
public static void main(String[]args){
int[]numbers=new int[6];
int highest=0;
Random rand = new Random();
for(int i=0;i<numbers.length;i++)
{
numbers[i]=rand.nextInt(100)+1;
highest += numbers[i];
}
Chapter8Number16.selectionSort(numbers);
Chapter8Number16.getMaxValue(array);
System.out.println("The sorted array: ");
for(int i=1; i<numbers.length;i++)
System.out.print(numbers[i] + "\t");
System.out.println();
System.out.println();
System.out.println("The highest number is: ");
System.out.println(maxValue[i]);
}
}

Your code has compilation issues, anyways, below code should help:
System.out.println("The highest number is: "+Chapter8Number16.getMaxValue(numbers));

You must save the maxvalue into a variable like
int max = Chapter8Number16.getMaxValue(array);
ora if you want just to print it:
System.out.println(Chapter8Number16.getMaxValue(array));

The maximum value is returned by your function,so you must assign it to a variable
int max = Chapter8Number16.getMaxValue(numbers);
System.out.println(max);

Related

Need to print an array in a different method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm running into an issue with my code and I can't figure out what's wrong. Basically the project I'm working on wants me to use static methods to perform a few different tasks using arrays. What I'm stuck on now, specifically, is printing my array.
The first thing I had to do was ask the user for the size of their array, and then have them input the data. After, I'm supposed to take the minimum value and maximum value, and then swap them. I'm pretty sure my code it right, but when I call the method I'm running into an error. This is what I have so far and I keep getting an error on lines 42 (beginning of swap method), 66 and 69:
public class ArraysStaticMethods {
static int[] array;
static public int arraySize;
static public int max;
static public int min;
//will create an array with user's input
private static int[] readInputs(int arraySize){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the length of your array: ");
arraySize = keyboard.nextInt();
array = new int[arraySize];
for (int i = 0; i <= array.length - 1; i++) {
System.out.print("Enter an integer: ");
int num = keyboard.nextInt();
array[i] = num;
}
//to test
System.out.println("Your array before:");
System.out.println(Arrays.toString(array));
return array;
}
//finds index of max and min values and swaps them
public static int[] swap(int[] array){
max = array[0];
min = array[0];
int maxIndex = 0;
int minIndex = 0;
for(int index = 1; index < array.length; index++){
if (array[index] > max){
max = array[index];
maxIndex = index;
}
if (array[index]<min) {
min = array[index];
minIndex = index;
}
}
array[maxIndex] = min;
array[minIndex] = max;
System.out.println("Your array after:");
System.out.println(Arrays.toString(array));
return array;
}
public static void displayOutputs(){
readInputs(arraySize);
swap(array);
}
public static void main(String[] args) {
displayOutputs();
}
}
You're never actually assigning the result of readInputs() to array, since you are hiding it inside that method. You're returning the local version, but not using that one either.
Instead of
int[] array = new int[arraySize];
at line 17, just do
array = new int[arraySize];
OR you can change your displayOutputs() method to assign the result of readInputs() to array, before passing it to swap().

trouble calling a method in the same class java

I've been asked to do the following problem:
Implement a method that accepts an array of integers as input and returns the sum of all of the elements in the array as output.
this is what i have(the entire program):
import java.util.*;
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
every time I try to call the method "sum" in the main method it gives me an error. I have tried every possible way I've seen on the internet to call the method. I'm not sure how I'm supposed to call it or if it is an issue because I have an array passed to the method.
Someone please help! and if you see that i've done something incorrectly, please let me know! thanks
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
// this works
System.out.println("sum is " + sum(array));
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}

Multiplying a array times 2 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the last method, computeTwice, I am trying to multiply the array that is inputed by 2, but instead of doing that it is listing the array in least to greatest order. Can someone please help me fix that issue.
Code :
import java.util.Scanner;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int numbers[] = new int[10];
for (int i = 0 ; i < numbers.length; i++ ) {
System.out.println("Enter a number");
numbers[i] = console.nextInt();
}
printReverse(numbers);
getLargest(numbers);
computeTwice(numbers);
}
public static void printReverse(int [] numbers) {
int [] revNumbers = new int[numbers.length];
for(int i = numbers.length -1; i >= 0; i--){
revNumbers[numbers.length - 1 -i] = numbers[i];
}
System.out.println("Here are you numbers in reverse: "+Arrays.toString(revNumbers));
}
public static int getLargest(int [] numbers){
int max = 0;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is: "+max);
Arrays.sort(numbers);
return max;
}
public static int[] computeTwice(int[] numbers){
for (int i = 0; i > numbers.length; i++){
numbers[i] *= 2;
}
System.out.println("The array with two times the numbers: "+ Arrays.toString(numbers));
}
}
Next time put a stack trace, since there is an error.
public static int[] computeTwice(int[] numbers){
for (int i = 0; i > numbers.length; i++){
numbers[i] *= 2;
}
System.out.println("The array with two times the numbers: "+ Arrays.toString(numbers));
}
}
How can i, the index of the array you are targeting, be greater than the length? Perhaps you meant
for (int i = 0; i < numbers.length; i++){
public static void computeTwice(int[] numbers){
for (int i = 0; i < numbers.length; i++){
numbers[i] *= 2;
}
One little error in your for loop. Look at your conditions. You initialized it correctly (i = 0), incremented it correctly (i++), but your condition is incorrect (i > numbers.length). You need to change it to
(i < numbers.length)
Also, when you create a method with a value type, you need to return that data type, otherwise create your method header with "void".
Since you created your method with the int[] value type, you need to return your int[], like so:
public static int[] computeTwice(int[] numbers) {
for(int i = 0; i < numbers.length; i++) { //note the condition change
numbers[i] = numbers[i] * 2;
}
System.out.println("The array with two times the numbers: " + Arrays.toString(numbers));
return numbers; //note the change by adding a return statement
}
}

How to find the largest value from an array in Java?

I am writing a program which can tracking three dices' total appears.Here are my codes:
import java.util.*;
class dice{
public static void main (String[] args){
Random rnd = new Random();
int[] track = new int[19];
for (int roll=0; roll<10000; roll++){
int sum=0;
for(int i = 0; i < 3; i++) {
//roll the 6-face dice
int n = rnd.nextInt(6) + 1;
sum+=n;
}
++track[sum];
}
System.out.println("Sum\tFrequency");
for(int finalSum=3; finalSum<track.length;finalSum++){
System.out.println(finalSum+"\t"+track[finalSum]);
}
System.out.println("the largest frequency is %d", //how to find it?)
}
}
Now I am almost done. But how can I find the largest appearance and print it separately? Thank you.
You can try below code:
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);
public int largest(int[] myArr) {
int largest = myArr[0];
for(int num : myArr) {
if(largest < num) {
largest = num;
}
}
return largest;
}
Set the variable largest to the first item in the array. Loop over the array, whenever the current num you're in is bigger than the current largest value, set largest to num.

Issues with Returning Array

So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).

Categories