arrays and static methods java - java

I have a question on how to call an array static method. In my case, I believe that my array static method is fine because the compiler does not complain about it, but it does when I call it, it says double cannot be converted to double[] How can I fix this? Any help will be greatly appreciated. Below is a snippet of my code:
// create allowed x values for calculation static method
public static double[] allowedValuesX(double[] x, double[] y, int choice){
double allowedVx[] = new double[choice];
int i = 0;
for(i = 0; i < allowedVx.length; i++){
if((Math.pow(x[i], 2) + (Math.pow(y[i], 2))) <= 1){
allowedVx[i] = x[i];
}
}
return allowedVx;
}
// main method
public static void main(String args[]){
// create Scanner object
Scanner in = new Scanner(System.in);
// call to promptUser
promptUser();
// create variable for recieving user input
int choice = in.nextInt();
double x[] = new double[choice];
int i = 0;
for(i = 0; i < x.length; i++){
x[i] = Math.random();
}
// call to allowed x values
allowedValuesX(x[i], y[j], choice);

You are passing specific array elements when calling allowedValuesX:
allowedValuesX(x[i], y[j], choice);
But you should pass the arrays themselves, to match the parameter types of the method:
allowedValuesX(x, y, choice);

Related

How to get the value from each index?

I'm extremely new to Java and we're tasked to take random values of an array and pass them through a method where it adds all of them for a running total.
For the sumMethod I'd like to take each value from all the index (given by sizeOfArray) and add them together.
Thank you!
public static void sumMethod(double[] arrayOfDoubles){
//How to get the value from each indexes (given by sizeOfArray) and add them for the sum
int arrayLength = arrayOfDoubles.length;
System.out.println(arrayOfDoubles);
}
public static void main(String[] args) {
//1-3: Set up Scanner object to collect user's input on the size of array.
Scanner keyboard = new Scanner(System.in);
System.out.println("How many double numerical entries do you have?");
//4: Declare an array of size sizeOfArray
int sizeOfArray = keyboard.nextInt();
//Initialize array
double[] arrayOfDoubles;
arrayOfDoubles = new double[sizeOfArray];
for(int i = 0; i < sizeOfArray; i++){
//5: Use the Random number Class and walk over the array
Random randomNum = new Random();
arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
//6: Invoke SumMethod
sumMethod(arrayOfDoubles);
}
}
}
public static void sumMethod(double[] arrayOfDoubles) {
double sum = 0;
for (int j = 0; j < arrayOfDoubles.length; j++) {
sum += arrayOfDoubles[j];
}
}
This will work too, if you are not familiar with the for-each loop yet.
Additionally, it is better to use arrayOfDoubles.length in the loop, in case you edit the code later, and change the size, or add or remove an element.
For sumMethod, I'd say the first thing you could do is give it a return value rather than void, (public static double sumMethod). That way when you run that method in main you can hold onto the result it prints out.
I may be wrong but my understanding is that your goal is to take an array and sum up the values within. For that purpose, the following would be a way to do it.
public static double sumMethod(double[] arrayOfDoubles) {
double total = 0;
for (double num : arrayOfDoubles) {
total += num;
}
return total;
}

Creating a method of type class Matrix to add two matrices

so, I'm supposed to make a matrix using HashMap<Integer,ArrayList<Number>>, where Number is a class who's instance variables are numerator and denominator.
Class Matrix inherits Class Number, which have methods like fillMatrix(), printMatrix(), addMatrix(Matrix,Matrix) and subMatrix(Matrix,Matrix), problem is in those last two methods, i made them but I'm pretty sure they are completely wrong since i get a NullPointerxception, How do i make such methods?
here is the code.
public class Matrix extends Number implements Calculation
{
public static int rows;
public static int cols;
private ArrayList<Number> myArray;
private ArrayList<Double> myArray2;
private ArrayList<Double> myArray3;
private ArrayList<Double> myArray4;
private HashMap <Integer, ArrayList<Number>> hm;
private HashMap <Integer, ArrayList<Double>> hm2;
public Matrix(int r, int c)
{
hm = new HashMap<>();
hm2 = new HashMap<>();
rows = r;
cols = c;
}
public void fillMatrix()
{
Scanner input = new Scanner(System.in);
myArray = new ArrayList<>();
myArray2 = new ArrayList<>();
System.out.println("Enter the number of rows");
rows = input.nextInt();
System.out.println("Enter the number of columns");
cols = input.nextInt();
Number n = new Number();
for (int i = 0; i < cols;i++)
{
n.setNumerator(i);
n.setDenominator(i+1);
myArray.add(new Number(i,i+1));
double xn = n.getNumerator();
double xd = n.getDenominator();
myArray2.add(xn/xd);
}
for (int i = 0; i < rows; i++)
hm2.put(rows,myArray2);
}
public void printMatrix()
{
for (int i = 0; i < rows; i++)
{hm.put(rows,myArray);
System.out.println(myArray3.toString());
}
}
public Number getItem(int rowNO,int colNO)
{
rows = rowNO - 1;
cols = colNO - 1;
hm.get(rows);
return myArray.get(cols);
}
public void addMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sum = a1+a2;
myArray3 = new ArrayList<>();
myArray3.add(sum);
}
x1=a;
x2=b;
}
}
public void subMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
{ x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sub = a1-a2;
myArray4 = new ArrayList<>();
myArray4.add(sub);
}
x1=a;
x2=b;
}
}
}
}
I'm a bit confused here, so I'll point out some things I noticed.
First off it's difficult to understand your code because of the variable names.
Also none of the methods are static, so i don't really understand why you're bringing in two Matrices for the calculation, then setting them equal to the first two you create in the beggining of both methods.
Next, you have two brackets after your for loop in the subtraction method, I'm guessing it was just a typo when pasting in StackOverflow.
The myArray objects you're adding the sum too is not going to be accumulating all the sums because you are creating a new arraylist each time that loop goes through. Create it outside the loop.
The NullPointerException could be anywhere really, it's hard to tell because the code is a bit confusing.
I would recommend using the LWJGL library which has has classes like Matrix4fand methods like Matrix4f.add();which will help you accomplish this.
Try running your program in debug mode so you can understand which statement gives you null pointer exception.
And I've noticed you have your rows and columns as static but you can change change them within constructor. It seems there is a logical mistake there. These two may be the cause of your exception if you didn't ever give initial value of them before.
If your matrixes can have different rows and columns then you definitely shouldn't use static for them.
To actually understand where nullpointerexception is given, you should also write your main code. But like I said, in debug mode, you can also see it yourself.

Random Numbers Test (Histogram)

I'm brand new to Java coding i'm trying to create a histogram with the following methods that were given to me. The comments are the instruction to each of our method that we will later use to create a main method and print a histogram. I have got up to method 3 and was able to compile everything fine but i'm not sure if i'm doing them right, I just know that they are compiling correctly up to method 4. I just don't know what to do for method 5.
/*
Method 1:
Find the maximun value in an array
*/
public static int max(int[]arr){
int maxValue = arr[0];
for ( int i=1; i < arr.length; i++ ){
if (arr[i] > maxValue){
maxValue = arr[i];
}
}
return maxValue;
}
/*
Method 2:
Compute a random integer in the range [a..b)
*/
public static int randomInteger(int a, int b){;
int randomNum;
randomNum = a+(int)(Math.random() * ((b-a)+1));
return randomNum;
}
/*
Method 3:
Draw a Simple histogram of the array arr.
*/
public static void drawHistogram(int[] arr){
for ( int i=0; i<arr.length; i++ ){
System.out.print((i*10+1)+"-"+(i*10+10)+":"+"\t");
for (int j=0; j<arr[i]; j++)
System.out.print("*");
System.out.println();
}
}
/*
Method 4:
Compute num random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
/*
Method 5:
Compute num pairs of random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doPairsTesting(int[] arr, int num, int range){
}
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("method1 = "+ max(test));
System.out.println("method2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("method4 = "+Arrays.toString(test));
}
It's fault design int random = int randomInteger(range); I think you need to read docs abot java basics.
I fixed method4 in next way:
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
For testing your methods, use next main method, it prints results to console or you can use Debugger in your IDE:
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("mathod1 = "+ max(test));
System.out.println("mathod2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("mathod4 = "+Arrays.toString(test));
}
And at last your method 5 must to return value of needed type or be void:
public static void doPairsTest(int[] arr, int num, int range){
}
For computing random integers, you might want to consider using the Random class. Here is some documentation: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
You can do this by declaring a Random object inside your class like this:
static Random randomGenerator = new Random();
And then within each of your methods, you can use randomGenerator.nextInt(n), where n will be the end of the range you want random numbers to be included. (exclusive of n, starting with 0).
For method 4, you probably want to set the return type to be an array. And then you can either leverage this randomGenerator, or given your current code, you'd have to pass in two parameters to your randomInteger method.
For method 5, you can simply use your doSingleTest method and then divide the entries of your array by 2 before returning the array. This works because if you find two 3s, your doSingleTest would have a frequency of 2 at the appropriate position. And dividing this by 2 would give you the number of pairs. Also you don't have to worry about odd numbers because the int type in Java simply drops remainders.
I also just noticed that you did not set a return type for method 5, so go ahead and set that to be int[]
And use a public static void main(String[] args) method to test your methods.
For method 5, are you referring to the dopairtest? In case so here is how I solved that:
static void doPairsTest(int[] arr3, int num2, int range3){
for (int i = 0 ; i < num2 ; i++) {
int rand2 = randomInteger(0, range3);
int rand3 = randomInteger(0, range3);
int randomPair = (rand2 * 10) + rand3 ;
System.out.println(randomPair);
arr3[randomPair] ++ ;
}
}
As you can see I just declared and assigned randomly generated values from my previous method into rand2 and rand 3 and then I added the two of them so they add up to a double digit.
Did you find out how to do the histogram? I am very confused on how to plot it based on the numbers and frequencies we generated.
public static void drawHistogram(int[] arr){
int n=0;
for (int i=1;i<=99;i++)
if (arr[i]>n)
n=arr[i];
for (;n>0;n--)
{
String r=" ";
for (int i=0;i<=99;i++)
if (n<=arr[i])
{
System.out.print(r+"*");
r=" ";
}
else
r+=" ";
System.out.println();
}
}

Method returning null is manipulating a final int array

Can anybody please explain to me why a method returning null is manipulating a final int [] ?
final int [] vals = {2,3};
int [] vals2 = multiply(vals);
for(int i : vals) System.out.println(i);
int [] multiply(int [] in){
for(int i = 0; i < in.length;i++){
in[i] *= 2;
}
return null;
}
Ouput:
4
6
Edit:
I have noticed this behavior only in methods returning an array. The same method returning an int doesn't change the original integers value...
Full code:
public class Main{
public Main(){
int [] myList = {56, 32, 200};
int [] newList = myList;
bubble_sort(newList);
for(int i : myList){ System.out.println(i); }
System.out.println();
for(int i : newList){ System.out.println(i); }
}
public int [] bubble_sort(int a[]){
int n = a.length;
int [] s = a;
for (int i = 0; i < n ; i++){
for (int j = n - 1; j >= (i+1); j--){
if (s[j - 1] > s[j]){
int t = s[j - 1];
s[j - 1] = s[j];
s[j] = t;
}
}
}
return null;
// return s;
}
public static void main(String [] args){
new Main();
}
}
Edit:
Following code produces following output as expected: 2, 4
int vals = 2;
int vals2 = multiply(vals);
System.out.println(vals);
System.out.println(vals2);
int multiply(int in){ return in*2; }
So my question is, why does a method returning an int does not change the input value, but a method returning an array does change the inputs original value(s).
Here, final means that the vals reference cannot be changed from referring to its initial array. But it says nothing about whether the contents of the array can be changed. As you see, they can be changed.
The final keyword will only stop you from assigning another array to vals, e.g.
vals = anotherArray; // Disallowed; final
A solitary return null; is useless. The multiply method should have been declared as void, returning nothing.
Arrays are mutable in java
the "final" keyword only stops you from reassigning, not from changing the actual value. It literally means that if you were to write "in = someOtherArray" somewhere in your code, you'd get a compile error.
This makes it sound like the "final" keyword is useless, but it works as expected for primitive types, or any immutable object.
If I have: int i = 0; I cannot change the 0 without reassigning a value to i.
Though you see the method returning null, the array contents are still getting modified within the multiply() method.
multiply(vals);
for(int i : vals) System.out.println(i);
Note that you are printing vals which has already been modified by the multiply method. (Java Pass by value)
So when i literally wanna use this method int [] newList = bubble_sort(myList); i mustn't modify the input value but saving each item into a new array int [] s = new int[a.length]; for (int i = 0; i < n ; i++)s[i] = a[i]; and then i can continue to sort the new array and return it. Then the original array(myList) won't be affected.

How to change 2d array by input?

I have a 2D array of 5 rows and 5 columns, all filled with the value 0. How can I make my program do this:
Enter any random combination of row and column like 2-5, without the [] brackets. Just typing 2-5 should be enough to make my program understand I mean row 2 column 5
Assign value I enter to said array in row-column combination.
This is what I got so far. As you can see I have only managed to output the values of all array elements.
import java.util.*;
public class stink {
public static void main(String[]args){
int[][] kuk = new int[5][5];
printMatrix(kuk);
}
public static void printMatrix(int[][] matrix)
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[row].length; col++)
System.out.printf("%2d", matrix[row][col]);
System.out.println();
}
}
}
you should use Scanner class from java API to get the inputs from the user like in the below code.
pass the inputs with a delimiter like if you want to have 2X3 array pass like 2-3 where '-' is a delimiter.
here are the links for String the and scanner java API.
Scanner sc = new Scanner(System.in);
System.out.println("please enter two numbers");
String inputs = sc.next();
int a=Integer.valueOf(inputs.split("-")[0]);
int b=Integer.valueOf(inputs.split("-")[1]);;
System.out.println(a + " " + b);
int[][] x = new int[a][b];
System.out.println(x.length);
this is not a copy/paste ready answer, but it should at least give you an indication on how you could handle this.
int rows = 0;
int columns = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Rows: ");
rows = scan.nextInt();
System.out.println("Columns: ");
columns = scan.nextInt();
int[][] kuk = new int[rows][columns];
import java.util.*;
public class stink
{
public static void main(String[]args)
{
int[][] kuk = new int[5][5];
// Where x and y are keys, integer is the integer you want to push
pushIntoMatrix(kuk, x, y, integer);
//kuk = pushIntoMatrix(kuk, x, y, integer); // Use if you want the method to return a value.
}
public static void pushIntoMatrix(int[][] matrix, int x, int y, int integer)
//public static int[][] pushIntoMatrix(int[][] matrix, int x, int y, int integer) // Use if you want to return the array.
{
matrix[x][y] = integer;
//return matrix; // Use if you want to return the array.
}
}
Since as you know, any data type in Java that's not a primitive is a reference, passing the kuk array into the method would affect the actual array reference. You can set a return in pushIntoMatrix() if you want, but you don't have to.

Categories