I'm a beginner in Java, I need to do this exercise for school:
Write a method that gets an array of numbers and returns an array with the index of the minimum and maximum values inside the array.
Example: for int[] arr = {70,16,-3,5,90}, the method will return {2,4}
My code is this:
public class MinAndMax {
public static int main (String[] args) {
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
return result;
}
}
I don't understand the error message, I know I can't transform an int into an int[], but I created a new int[] here, so I don't see the error.
You should not return result array like that. Because you are writing that inside the void main function.
you code should do something like below,
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MinAndMax
{
public static void main (String[] args) throws java.lang.Exception
{
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
System.out.println(Arrays.toString(result));
}
}
You get the error incompatible types: int[] cannot be converted to int because the main method has a int return type but you return int[].
To resolve the problem, use the standard main method signature public static void main (String[] args) since this allows the compiler to run the main method when you run the .java file.
To print the min and max values, you could extract the logic for finding min and max values to a separate method (e.g., getMinAndMaxValueIndices) and call it from the main method:
import java.util.Arrays;
class Main {
public static void main (String[] args) {
int[] minAndMaxValues = getMinAndMaxValues();
// print individual elements
int min = minAndMaxValues[0];
int max = minAndMaxValues[1];
System.out.println("min="+min+"\n"); // prints min=1
System.out.println("max="+max+"\n"); // prints max=3827
// print the array
System.out.println(Arrays.toString(minAndMaxValues)); // prints [1, 3827]
}
private static int[] getMinAndMaxValues() {
int[] myArray = {2,7,32,89,32,1,56,73,99,3827,56};
int min = myArray[0];
int max = myArray[0];
for (int i=0; i<myArray.length; i++) {
if (myArray[i]<min) {
min = myArray[i];
}
else if (myArray[i]>max) {
max = myArray[i];
}
}
int[] result = new int[2];
result[0] = min;
result[1] = max;
return result;
}
}
Related
Our assignment says we should "write the source code and test code for a function named sumArray that accepts an array of ints and returns the sum of all elements from the array".
I think I've got SumArray.java to return sum OK, but I'm struggling to apply my method to the test input. Any help please? TIA.
SumArray.java
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
SumArrayTest.java
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
/**
* Test of main method, of class SumArray.
*/
#Test
public void testMain() {
System.out.println("main");
String[] args = null;
SumArray.main(args);
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
// int testResult = sumArray({2, 3, 4});
int testResult = SumArray sumArray(intArray);
assertEquals(expectedResult, testResult);
// fail("The test case is a prototype.");
}
}
Edit: I've tried to implement what's been suggested so far with some changes; really not sure of any of this is right; a lot of it is guesswork TBH.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray;
public static int sumArray(int[] arr) {
return sum;
}
public static SumArray input() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return new SumArray();
}
public static void main(String[] args) {
SumArray result = input();
System.out.println(result.sumArray(SumArray));
}
}
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
#Test
public void testSumArray() {
System.out.println("main");
String[] args = null;
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
assertEquals(expectedResult, SumArray.sumArray(intArray));
// fail("The test case is a prototype.");
}
}
The only error I'm seeing currently is 'cannot find symbol' for SumArray in main.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
The above is the original code you posted. Now, you say you get the correct output. Yes, here you do:
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray(); // this one will return the correct answer
sumArray(); // this one will not
}
}
The second one will return wrong data, because you don't reset the value of sum.
You should split the tasks: sumArray should receive an array, and should return the sum of the elements. Either you should change the name of the method, or change the implementation, that is what Mahmoud told you.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static Scanner scan = new Scanner(System.in); // create this on class level, not every execution of your method
public static int[] buildArray(int elements) {
int[] arr = new int[elements];
for ( int i = 0; i < elements; i++ ) {
System.out.println("Enter element nr: " + (i+1));
arr[i] = scan.nextInt();
}
return arr;
}
public static int sumArray(int[] input) {
int sum = 0; // don't use a class level one. especially not a static one, it's value could be altered by another thread
for ( int in : input ) { // iterate over the array and add the values
sum += in; // this should be in -> each iteration we add the value of in (the element of the array) to sum
}
return sum;
}
public static void main(String[] args) {
System.out.println("Provide the size of the array: ");
int param = scan.nextInt();
int[] array = buildArray(param);
int result = sumArray(array);
System.out.println("The sum of the array is: " + result);
}
}
This approach will land you with far lesser issues. It also doesn't have static variables like n and sum in your class that might lead to wrong results.
The main() method is the entry point into the application, you shouldn't test the main() method. Instead, you should test the sumArray() method and compare the expected Vs. the actual returned value from the method.
As a side note, you can better pass the input array to the sumArray() method as a parameter instead of reading it from System.in within the method body.
So your method signature can look like this:
public static int sumArray(int[] arr). The client code which uses this method, which is the main method in your case (or the unit test) can pass the array without bothering the method how this input array was got.
having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
}
}
return arrayX;
}
}
you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress
import java.util.*;
public class Help
{
public static void main(String[] args)
{
ArrayList<Integer> arraysA = new ArrayList<Integer>();
arraysA.add(Integer.valueOf(2));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(19));
arraysA.add(Integer.valueOf(32));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(18));
arraysA.add(Integer.valueOf(25));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(3));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
int varB=8;
newSmallerArray(arraysA,varB);
for(Integer i:arraysA)
{
System.out.println(i);
}
}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
for(int i=0;i<arraysA.size();++i)
{
if(Integer.valueOf(arraysA.get(i))==varB)
{
arraysA.remove(i);
}
}
}
}
Try this code it will not require for loop:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);
I'm having trouble initializing an Array and don't really understand how to do it.
public class Array {
int[] array;
public Array(int[] array) {
this.array = array;
}
public int sum() {
int sum = 0;
for (int i = 0; i < this.array.length; i++) {
sum = sum + array[i];
}
return sum;
}
public double average() {
double av = this.sum() / this.array.length;
return av;
}
public static void main(String[] args) {
Array a = new Array[3];
}
}
I keep getting an error that says required: Array found: array[]
I want to make a scanner and have user input on the array but I don't even know how to initialize it in the first place
You have to change
Array a = new Array[3];
To
Array a = new Array(new int[3]);
Constructor of Array is taking int[] as input arguments.
I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.
Can someone please help me figure out what I am doing wrong here.
import java.util.Random;
public class SortedArray
{
int randomValues;
int[] value;
public SortedArray()
{
}
public int getRandom()
{
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues = random.nextInt(100);
}
return randomValues;
}
public int getArray()
{
int result = 0;
value = new int[randomValues];
for(int item : value)
{
System.out.println("The array contains " + item);
}
return result;
}
}
Here is my main method
public class ReturnSortedArray
{
public static void main(String[] args)
{
SortedArray newArray = new SortedArray();
int random = newArray.getRandom();
int array = newArray.getArray();
System.out.println(array);
}
}
In your method getArray
the code
value = new int[randomValues];
is simply creating a new empty int array of size ramdomValues.
As the default value of an int is 0, that is what you are getting
Also in your method getRandom you are setting the same value time and time again
for (...)
randomValues = random.nextInt(100);
try
public int[] getRandomArr()
{
int randomValues [] = new int [20];
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues[j] = random.nextInt(100);
}
return randomValues;
}
I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,
public class SortedArray {
private Random random = new Random();
private int[] value = new int[20];
public SortedArray() {
super();
setRandomValues();
}
public void setRandomValues() {
for (int j = 0; j < value.length; j++) {
value[j] = random.nextInt(100);
}
}
public int[] getArray() {
return value;
}
}
And then your main method, should be updated like
public static void main(String[] args) {
SortedArray newArray = new SortedArray();
int[] array = newArray.getArray();
System.out.println(Arrays.toString(array));
}
I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH