Set Array method to accept a fixed amount? [duplicate] - java

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 5 years ago.
I am trying to write an app that will set a fixed array of a any size and then pass that into the method as a parameter.
package com.company;
public class NumberManipulation {
double [] array = {500,250,-350,124,87};
double minimum = Double.MIN_VALUE;
double maximum = Double.MAX_VALUE;
public void getMaximum() {
for (int i = 0; i < array.length; i++) {
if (array[i] > minimum) {
minimum = array[i];
}
}
System.out.println(minimum);
}
public void getMinimum() {
for (int i = 0; i < array.length ; i++) {
if (array[i] < maximum){
maximum = array[i];
}
}
System.out.println(maximum);
}
}
package com.company;
public class Main extends NumberManipulation {
public static void main(String[] args) {
NumberManipulation number = new NumberManipulation();
number.getMaximum();
number.getMinimum();
}
}
I know that I can set an array to a fixed amount via:
double [] array = new double [10] //if I wanted the array to be 10 indexes
I can't figure out how to pass that into the getMin and getMax methods, though.
Just for the record, I was able to solve to the problem on my own. The recommendation provided with the link was not adequate for the answer. Here is a link it (https://gist.github.com/BrianARuff/4c49aee1a5644fee35e80b2547e6c74d)

I think you are searching something like this function
Arrays.copyOfRange(arr, i, j);

Related

How to avoid creating duplicates in array made by math.random numbers in Java? [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 4 years ago.
I have a method that creates an array with a length decided by a parameter in Main. The numbers are created by math random. How do I avoid duplicated by checking the created random number before putting it inside the array each time?
Is it possible to check an unfinished array?
class Test{
public int[] numberArray;
public int length;
public Test(int lengthArray){
this.numberArray=new int[lengthArray];
this.length=lengthArray;
}
public boolean checkArray(int checknumber){
inArray=false;
//what code can I write here to find duplicate
return inArray;
}
public void fillArray(){
int highest = 1000;
int lowest = 100;
int randomNumber = 0;
int counter=0;
for(int i=0;i<length;i++){
randomNumber=lowest + (int)(Math.random() * ((highest - lowest) + 1));
numberArray[counter]=randomNumber;
counter++;
}
}
public class testing {
public static void main(String[] args) {
Test test1 = new Test(9);
test1.fillArray();
for(int value: test1.numberArray){
System.out.print(value+" ");
}
}
}
You could first create all the numbers you need and store in a Set data structure till size equals the number of numbers you want. Later, transfer all the numbers in the Set to an array of the same size

Creating a method to print an array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
I am trying to find a way to print the contents of the array, while using a for loop. This is a fairly new section in java to me, as I am a beginner. Any help is appreciate in concerns to my question. My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray( ) {
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
}
}
My question is would I move the "Random" assessor method into the
mutator method or am I just completely wrong and have to do something
else.
You don't have to. Just use a loop to iterate through the array which is already filled in the constructor.
public void printArray( ) {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
System.out.println(arr[i]);
}
}
By the way, with Java 8, you can write less lines of code to achieve the same result:
Arrays.stream(arr).forEach(System.out::println);
public void printArray() {
//Print array
System.out.println(Arrays.toString(arr));
//another method with for loop
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i])
}
}
Note there is plenty of other techniques
In terms of writing clean code, it would probably be good to move this bit of code into its own private method within the class, and calling that within the constructor.
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
populateArray();
}
private void populateArray() {
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
Then in your printArray() method you can loop through the array and call System.out.println( ) for each item.
public void printArray( ) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
If you come from a more functional background, I can show you how to write this more functionally using Java 8 lambdas. Let me know.

Array out of bounds exception for basic array [duplicate]

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
How do I declare and initialize an array in Java?
(31 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
For some reason the size of my array is invalid and I am not sure how I should change NextIndex to fix this. The size should be dynamic and changing NextIndex to 1 doesn't help it.
/**
* Code for E7.9
* #Michael Goedken
*/
public class DataSet
{
// Implmentation
int nextIndex = 0;
double[] list = new double[1];
public static void main (String args[])
{
DataSet data = new DataSet(5);
data.add(3.5);
data.add(7.9);
data.add(15.2);
data.add(-7.3);
System.out.println("Sum: " + data.getSum());
System.out.println("Expected: 19.3");
System.out.println("Average: " + data.getAverage());
System.out.println("Expected: 4.825");
System.out.println("Maximum: " + data.getMaximum());
System.out.println("Expected: 15.2");
System.out.println("Minimum: " + data.getMinimum());
System.out.println("Expected: -7.3");
}
Constructs an empty data set.
#param maximumNumberOfValues the maximum this data set can hold
public DataSet(int maximumNumberOfValues)
{
double[] list = {maximumNumberOfValues};
}
Adds a data value to the data set if there is room in the array.
#param value a data value
public void add(double value)
{
list[nextIndex] = value;
nextIndex++;
}
Gets the sum of the added data.
#return sum of the data or 0 if no data has been added
public double getSum()
{
double sum = 0;
for (double i : list)
sum += i;
return sum;
}
Gets the average of the added data.
#return average of the data or 0 if no data has been added
public double getAverage()
{
double sum = 0;
double avg = 0;
for (double i = 0;i<list.length;i++)
sum += i;
avg = sum/list.length;
return avg;
}
Gets the maximum value entered.
#return maximum value of the data
NOTE: returns -Double.MAX_VALUE if no values are entered.
public double getMaximum()
{
double max = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] > max)
{
max = list[i];
}
}
return max;
}
Gets the minimum value entered.
#return minimum value of the data
NOTE: returns Double.MAX_VALUE if no values are entered.
public double getMinimum()
{
double min = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] < min)
{
min = list[i];
}
}
return min;
}
}
public DataSet(int maximumNumberOfValues) {
double[] list = {maximumNumberOfValues};
}
Here, list s a local variable declaration (and only has one element), which has nothing to do with the member variable of the same name.
Also this expression {maximumNumberOfValues} actually means "create an array with a single element with value maximumNumberOfValues"
Assign a value to the member variable instead, where that value is a new array with the desired number of elements:
list = new double[maximumNumberOfValues];
Change
int nextIndex = 0;
double[] list = new double[1];
to
int nextIndex = 0;
double[] list;
Change your constructor from
public DataSet(int maximumNumberOfValues)
{
double[] list = {maximumNumberOfValues};
}
to
public DataSet(int maximumNumberOfValues)
{
list = new double[maximumNumberOfValues];
}
I am not quite sure what your problem is.
int nextIndex = 0;
double[] list = new double[1];
I might be wrong... but your array is always the size of 1.
And as Ervin Szaligyi said -> you have to create the array differently
double[] list = {maximumNumberOfValues};
That's not how you create and allocate array in Java with the size of maximumNumberOfValues.
You should allocate it like this: double[] list = new double[maximumNumberOfValues];
Update: Also, double[] list = {maximumNumberOfValues}; should be declared like this in the constructor: list = new double[maximumNumberOfValues], otherwise you are declaring a local variable. You should declare list as private outside of your constructor.

Getting NullPointerException in when array's size is not instantly assigned

I'm trying to learn Java and I am currently writing a program that will split an array of integers into two sub-arrays, one containing the positive values and the other the negative values.
Due to the fact that the sizes of the two sub-arrays can not be specified from the start (because this program should work on any array of integers) I wrote two methods which will calculate the sizes of the two sub-arrays (maxNeg and maxPos). Afterwards, the two sub-arrays (arrayNegative and arrayPositive) are initialized having the the two corresponding sizes.
The problem is that, when I try to populate the two arrays using the arraySorter(), the compiler gives me the ArrayIndexOutOfBoundsException: 0 error right at the first iteration inside the arraySorter() method.
Note 1: The issue doesn't occur when values are assigned to the maxNeg and maxPos variables from the start.
Note 2: I know this type of problem is usually solved using ArrayLists for storing the positives and negatives, but my assignment's requirements force me to do this using only arrays.
public class sortMethod {
public int max; // max = main array length
public int maxNeg; // the length of the final array that will store the
// negative integers
public int maxPos; // the length of the final array that will store the
// positive integers
public int[] intArray = new int[max];
public int getMaxNeg() {
for (int i = 0; i < max; i++) {
if (intArray[i] < 0) {
maxNeg++;
}
}
return maxNeg;
}
public int getMaxPos() {
for (int i = 0; i < max; i++) {
if (intArray[i] >= 0) {
maxPos++;
}
}
return maxPos;
}
public int[] negativeArray = new int[maxNeg];
public int[] positiveArray = new int[maxPos];
public int negIndex = 0;
public int posIndex = 0;
public void arraySorter() {
for (int a = 0; a < max; a++) {
if (intArray[a] < 0) {
negativeArray[negIndex] = intArray[a];
negIndex++;
// System.out.println(negativeArray[0]);
} else {
positiveArray[posIndex] = intArray[a];
posIndex++;
}
}
}
public sortMethod(int[] y, int z) {
this.intArray = y;
this.max = z;
}
Can someone explain why I'm keep getting the NullPointerException when using formulas to calculate the sizes of the two sub-arrays and why I don't get the error when values are assigned to 2 variables upon declaring them.
This is the main method where I created the test object:
public class ArraySort {
public static void main(String[] args) {
int[] array = { -12, 23, -22, 0, 43, -545, -4, -55, -43, -12, 0, -999};
int z = array.length;
sortMethod arrayTest = new sortMethod(array, z);
arrayTest.getMaxNeg();
arrayTest.getMaxPos();
arrayTest.arraySorter();
}
Thanks and please excuse me if my question's formating is not compliant with the site's standards, it's my first and I will try to improve in the future.
When this code is executed
public int[] negativeArray = new int[maxNeg];
public int[] positiveArray = new int[maxPos];
maxNeg and maxPos is equal to 0, so it is normal to have an out of bound exception.
To get it to works, you could initialize the arrays directly in the method so your code would become :
public int[] negativeArray;
public int[] positiveArray;
public int negIndex = 0;
public int posIndex = 0;
public void arraySorter() {
negativeArray = new int[maxNeg];
positiveArray = new int[maxPos];
for (int a = 0; a < max; a++) {
if (intArray[a] < 0) {
negativeArray[negIndex] = intArray[a];
negIndex++;
} else {
positiveArray[posIndex] = intArray[a];
posIndex++;
}
}
}
Another part of your code that is wrong is the constructor of sortMethod. You give the array length to the maximum bound, but the maximum bound is actually length - 1. so change this.max = z; to this.max = z - 1; 
Also, your algorithm does not sort numbers, it simply separate negatives of positives... If you want to sort an array of number you can simplify it in one line :
Arrays.sort(array);
The order in which you define variables and methods in Java is not important. Your instance variables (e.g. your negativeArray and positiveArray) are created as soon as the class instance is created (and before the constructor is called). You therefore initialize both arrays with a size of 0.

Java program which accepts Integer array as parameter and randomise its values [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I tried a program where I take an integer array and randomise values in it. but I am not able to understand why but am getting a crazy output which displays special characters and all. what's wrong with my question. Here is my code:
import java.util.Random;
public class Q2d {
public static void shuffle(int[] arr) {
int n = arr.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
int temp = arr[i];
arr[i] = arr[change];
arr[change] = temp;
}
}
public static void main(String args[]) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
shuffle(arr);
System.out.println(arr);
}
}
You are attempting to print the array object. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "crazy output".
Use Arrays.toString():
System.out.println(Arrays.toString(arr));
I'm pretty sure you asked this question like 20 minutes ago and in it instead of
System.out.println(arr);
you had
for(int i:arr){
System.out.println(i);
}
which is correct...

Categories