Need some advice for a project in an intro Java class. I'm stuck at creating a assignment constructor which takes an array as input and completes a deep copy. The constructor in question is found in the second block of code.
import java.util.Scanner;
public class NumberList
{
public static final int MAX_CAPACITY = 100;
private double [] numbers;
private int length;
public NumberList()
{
numbers = new double[MAX_CAPACITY];
int i;
for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = 0;
length = 10;
}
Everything before this line compiles. The constructor below is to complete a deep copy from the array parameter to the numbers array.
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
Following errors received:
NumberList.java:67: error: '.class' expected
numbers = a[];
For the life of me, I cannot figure out how to do fix this. I've tried with a "for" loop, as well.
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
The first line is attempting to re-declare the parameter a; you can't do that.
And the second line uses an invalid syntax: you never use [] except in the declaration of array variables, or the initialization of those variables.
The easiest way to copy a is to write:
numbers = Arrays.copyOf(a, a.length);
But you can write this with a loop like Mureinik shows you.
Note that you should write double[] a, not double a[]. The two are semantically identical, but the former is preferred because [] is part of the type, not the variable name.
The double a[]-style was put into Java "as a nod to the tradition of C and C++". You can read more here.
You can simply use:
NumberList(final double[] a) {
numbers = Arrays.copyOf(a, a.length);
}
Just run over a and copy its elements to numbers:
public NumberList(final double[] a) {
this.numbers = new double[a.length];
for (int i = 0; i < a.length; ++i) {
this.numbers[i] = a[i];
}
}
Related
import java.util.Scanner;
public class AddElementToSpecificPosition {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int[] array =arrayDetails();
scanner.nextLine();
System.out.println("Enter the position for the element \r");
int position = scanner.nextInt();
System.out.println("Enter the element \r");
int element = scanner.nextInt();
addElementToSpecificPositoin(array,position,element);
}
//getting details form user for arry
private static int [] arrayDetails() {
System.out.println("Enter the length for the array \r");
int length = scanner.nextInt();
scanner.nextLine();
int [] intArray = new int[length];
System.out.println("Enter the numbers for the array \r");
for(int i=0; i<intArray.length; i++) {
intArray[i] = scanner.nextInt();
}
return intArray;
}
//trying to add an element to specific position
private static void addElementToSpecificPositoin(int[] array, int position, int element) {
int lastIndexValue = array[array.length-1];
for (int i=array.length-1; i>position-1 ; i-- ) {
array[i]=array[i-1];
}
array[position-1] = element;
int addedPosition = array.length ;
int [] newArray = new int[addedPosition+1];
for (int i =0; i<newArray.length; i++) {
newArray[i] = array[i];
}
newArray[addedPosition] = lastIndexValue;
for (int j =0; j<newArray.length; j++) {
System.out.println(newArray[j]);
}
}
}
Arrays are fixed sized, and java is pass-by-value. Passing an array variable will never assign to that variable.
private static int[] insert(int[] array, int position, int element) {
int[] largerArray = Arrays.copyOf(array, array.length + 1);
System.arraycopy(largerArray, position, largerArray, position + 1,
array.length - position);
largerArray[position] = element;
return largerArray;
}
array = insert(array, 13, 42);
The above uses a class Arrays with nice utility functions. And System.arraycopy is a fast function to copy array slices. It also deals with overlapping slices.
You need to assign to the passed in array variable the resulting larger array.
array is size X. Whatever it might be, let's call it X. Then you do:
int addedPosition = array.length;
int[] newArray = new int[addedPosition + 1];
In other words, newArray has size X+1. You then loop through 0 through newArray.length and resolve array[i] for each i. This, of course, means array[X] is resolved which is a non-existing entry.
Instead of asking on SO, you should invest a little bit of time and learn to debug. It's easy! All you really do is figure out what a line of code should be doing (by just looking at it and basically 'being the computer'. Use pen and paper if you prefer), then run the code line by line and check that the code actually does what you think it should.
If, thinking it through line by line and working it out, you realize the code isn't what you wanted: Great, you found a bug. Fix it and keep applying this process. Otherwise, you'll figure it out when what the code actually does, does not match what you thought it would. Debuggers help a ton when doing this, but a boatload of System.out.println statements can help, too. You'd have figured it out once you realize with e.g. an example input of a 4-size array ends up running newArray[4] = array[4].
I wanted to create two-dimensional matrixes on an automated routine (depending on inputs) and then make them return to see the results.
Here's my code:
public class Two_dimensional_arrays {
static int[][] array1;
public static int[][] create_array(int number1, int number2) {
int k = 1;
for (int j = 0; j <= number2; j++) {
for (int i = 0; i <= number1; i++) {
array[i][j] = k;
k++;
}
}
return array1;
}
}
The logic behind all of that was to fill any matrix in order like (let's make a 3x3 one)
1-2-3
4-5-6
7-8-9
So the matrix would be automatically filled (in ascending order), but it didn't work out as expected since I'm kind of new to programming.
You have to actually allocate the array somewhere.
static int[][] array1;
This declares a variable capable of holding a reference to an array; it is not the array. The array is allocated by 'new':
static int[][] array1 = new int[3][3];
A couple of other points:
The 'array' in your loop should probably be 'array1'.
Since 'array1' is a member variable there's probably no point in returning it as well. You could go either way: have a single array, as at present, and your create_array method will overwrite it each time; OR have create_array allocate an array of the intended size (new int[number1][number2]) and return it. I'd go for the latter.
The arguments could be named better: 'row_count' rather than 'number1', 'column_count' rather than 'number2' -- or anything similar that conveys the intended meaning. (Typically Java programmers use camel-case names, like rowCount, rather than underscore, but that's not a particularly interesting discussion and not my point here).
public class Two_dimensional_arrays {
public static int[][] create_array(int number1, int number2){
int[][] matrix = new int[number1][number2];
int k = 1;
for(int i = 0; i<number1; i++){
for(int j = 0; j<number2; j++){
matrix[i][j] = k;
k++;
}
}
return matrix;
}
}
I'm a beginner in Java and trying to get the sum of all the elements in the ArrayList. I'm doing it by using a method and get this error in the method:
"bad operand types for binary operator '+' first type: int, second
type: Object"
I don't know what I'm doing wrong here, appreciate any help!
public static int sumNumbers(<ArrayList> numbers){
int sum = 0;
for(int i = 0; i<numbers.size(); i++){
sum+=numbers.get(i);
}
return sum;
}
As others have pointed out, you need to give your ArrayList a type. You can then use native streams to make the code a little more compact:
ArrayList<Integer> numbers = ... ;
numbers.stream().mapToInt(i -> i).sum();
// create a list
List<Integer> ints = Arrays.asList(1, 2, 3);
// get the sum of the elements in the list
int sum = MathUtils.sum(ints);
Declare numbers as ArrayList<Integer> numbers.
Then the Integer will be unboxed to int. Right now, your arraylist contains objects that may not be ints.
For the moment, numbers.get() will return an object, and you can not add an object to an int directly.
You could always cast the element to Integer, but I would recommend the first option.
This will works fine.
import java.util.ArrayList;
public static int sumNumbers(ArrayList<Integer> numbers){
int sum = 0;
for(int i = 0; i<numbers.size(); i++){
sum+=numbers.get(i);
}
return sum;
}
Or
public static int sumNumbers(ArrayList<Integer> numbers){
return numbers.stream().mapToInt(n->n).sum();
}
I need practice with my syntax. I have an array of numbers and with that are methods to find the average, report highest number, and report the lowest number. To report the highest/lowest numbers I will be sorting the array.
But first my problem is with reporting the average. I think that if I can understand that part, then the min/max will be no problem. I have tried changing it to say Driver.randomArray[].getAverage() as well.
Are there any suggestions? Thanks in advance.
~Crystal
error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
randomArray cannot be resolved to a type
Class cannot be resolved to a type
Syntax error, insert ". class" to complete Expression
at IntegerArray.main(IntegerArray.java:48)
and it refers to my attempt to call the average from this line,
System.out.println(randomArray[].getAverage());
First, Driver Class
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver(){
int[] randomArray = new int [MAX];
int sum;
final int MAX;
}
public int getAverage(){
for (int index = 0; index < MAX; index++){
int sum = 0;
int[] randomArray = null;
int average;
sum = sum + randomArray[index];
average = sum/MAX;
return average;}
}
public void sortArray(){
// sort the array from smallest to biggest
int[] randomArray;
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println( + number)}
}
public int getMin(){
int[] randomArray;
// find the lowest number
return randomArray[0];
}
public int getMax(){
int[] randomArray;
// find the highest number
return randomArray[MAX];
}
}
Then my main class:
import java.util.Random;
import java.lang.reflect.Array;
import java.util.Arrays;
public class IntegerArray {
public static void main (String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int [MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() *10);
// prints the array
for (int value : randomArray)
System.out.println (value);
System.out.println("The length of the array is: " + randomArray.length);
System.out.println(randomArray[].getAverage());
}
}
The way you're creating your methods eg. getAverage() you can't call it on the array you created. On the other hand you can call them on the a Driver object you create. for example: Driver driver = new Driver(); System.out.println(driver.getAverage()); If you want to call them on the Array Object you should add them on the Array class (but that is something more advanced Java than this).
In Java Code you need to add a ; after a statement don't forget them ;). Your IDE should warn you about them.
When you create your getMax() method you should add the array as a parameter. So that the method knows for what Array object it should get the highest number. For example:
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
This counts for all your methods.
I hope this solves some of your answers if not please add a comment or something.
So here is your code after that:
Driver class:
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver() {
int[] randomArray = new int[MAX];
int sum;
final int MAX;
}
public int getAverage() {
int average = 0;
for (int index = 0; index < MAX; index++) {
int sum = 0;
int[] randomArray = null;
sum = sum + randomArray[index];
average = sum / MAX;
}
return average;
}
public void sortArray(int[] randomArray) {
// sort the array from smallest to biggest
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println(+number);
}
}
public int getMin(int[] randomArray) {
// find the lowest number
return randomArray[0];
}
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
}
IntegerArray class:
public class IntegerArray {
public static void main(String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int[MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() * 10);
// prints the array
for (int value : randomArray)
System.out.println(value);
System.out.println("The length of the array is: " + randomArray.length);
Driver driver = new Driver();
System.out.println(driver.getAverage());
}
}
Reply to the question in the comments:
You should give the randomArray as the parameter with your getAverage method so that method knows on which array it should operate, example: driver.getAverage(randomArray);
Your getAverage method also has some flaws:
1. Your sum variable should be outside the loop because else you would set your sum to 0 every time you iterate inside the loop.
2. int[] randomArray = null; You shouldn't really do this line at all, this line will create a NEW int array and set its value to null while you should you use the int array you give as a parameter.
So your getAverage method becomes:
public int getAverage(int[] randomArray) {
int sum = 0;
for (int index = 0; index < randomArray.length; index++) {
sum = sum + randomArray[index];
}
int average = sum / randomArray.length;
return average;
}
Currently your main class doesn't reference Driver at all, so your code cannot be called.
System.out.println(randomArray[].getAverage());
On this line randomArray is still just an array of integers (int[] randomArray = ...).
You will need to create an instance of Driver, pass in whatever array you're wanting to use, and then do .getAverage() on that.
randomArray is null and you are trying to read from a null array.
you need to define randomArray as a class member, not a local variable in all functions.
Local variables inside functions cannot be used as soon as function ends, and using the same name in other functions cannot help that.
Also:
define sum and average before loop. calculate and return average after loop.
Among other things your main issue seems to be a fundamental misunderstanding of scope rules. For example:
void method () {
int someVariable;
}
void method2 () {
someVariable = 2; // <-- Error.
}
In that code someVariable is local to method and is not available outside of it. You could not access it in method2.
I suggest you have a read not only of the above scope rules link, but of the official tutorial on member variables as well, which also describes scope. The information there will help you come up with a final strategy.
In your specific case your two most reasonable options are:
You could make randomArray a member field of your class (see above links).
You could pass randomArray as a parameter to your various methods (e.g. as a parameter to getAverage, see also the official tutorial on passing information to a method).
You have a few other issues, some mentioned in the other answers here, but my take is that is your primary confusion here. Read through the official tutorials (the docs.oracle.com links above), they're concise and well-written, and will fill in the blanks of some of your missing concepts. After you do that, give it another shot.
By the way, as for your compiler error on:
System.out.println(randomArray[].getAverage());
Unfortunately randomArray[].getAverage() simply does not make enough sense to justify a full explanation of how the compiler is interpreting it, so suffice it to say: No, that's wrong. :)
You'll want to check out that "passing information to a method" tutorial mentioned above, because it looks like you're trying to express something like this (option 2 above):
int getAverage (int randomArray[]) {
...
}
System.out.println(getAverage(randomArray));
As an aside: Note that the average of a bunch of integers isn't necessarily an integer itself (the average of 1 and 2 is 1.5). You might consider computing and returning a float or a double instead.
I am trying to find the minimum value in an array by way of creating a new Java class. I am having trouble passing in the array and using it to find the minimum value of an array.
I have a total of two separate arrays that I am trying to find the value of.
Here is the first class I created:
import java.util.*;
public class mooseWeight
{
public int main(String[] args)
{
int[] length1;
int[] length2;
length1 = new int[20];
length2 = new int[50];
//Length 1
System.out.println("Array 1:");
Random rnd = new Random();
for(int i = 0; i<length1.length; i++)
{
length1[i] = rnd.nextInt(400) + 250;
System.out.println(length1[i]);
return length1[i];
}
System.out.println("-----------------------------------");
//Length2
System.out.println("Array 2:");
Random rnd2 = new Random();
for(int j = 0; j < length2.length; j++)
{
length2[j] = rnd2.nextInt(400) + 250;
System.out.println(length2[j]);
return length2[j];
}
}
}
This is currently set up to find the minimum value of length1[] (aka the first array).
This is the class I am trying to pass the arrays into:
public class minWeight
{
public static int getArrayMin(int[] arr)
{
mooseWeight array1[] = new mooseWeight[];
int minValue = array1[0];
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < minValue)
{
minValue = array1[i];
}
//return minValue;
}
return minValue;
System.out.println(minValue);
}
}
My current error:
1 error found:
File: D:\2016-2017\Fall2016\201_CSCE_Programming\Lab 7\minWeight.java [line: 5]
Error: array dimension missing
The error in minWeight not fom the array parameter, it is from this line:
mooseWeight array1[] = new mooseWeight[];
You cannot allocate an array of unknown dimension in java.
Also, your attempt to do so makes no sense.
Just delete the line above from your java method and change the name of the parameter to array1.
Get an IDE like netbeans or eclipse.
Your mooseWeight class contains your main, so when you're creating array1, you're trying to create an array containing your actual program.
mooseWeight array1[] = new mooseWeight[]; is creating an array of mooseWeight objects.
As you don't define a size, this will fail, but even if it didn't, it wouldn't work.
I assume that you meant to create an array of int, then loop over it.
If you created an array of int, then tried to loop over it without adding anything, the loop won't do anything as there's nothing to iterate over.
In your method, you pass in an array of int called arr, so you need to use that to loop over.
If you're trying to pass 2 arrays into the method, creating an array as part of your method still won't work.
You need to modify your method declaration to accept a second array.
Assuming you want to find the smallest value from both of these arrays, I've modified my code snippet to do just that.
If you need to process your second array differently, modify the loop which deals with secondArr.
As mentioned in comments, your mooseWeight class should be named MooseWeight to keep with correct Java naming conventions.
A class name is in PascalCase, with instances in camelCase.
To call the method, use the following snippet.
int[] ar1 = new int[20];
int[] ar2 = new int[50];
//Populate your arrays with values....
int minValue = MinWeight.getArrayMin(ar1, ar2);
Class:
public class MinWeight {
public static int getArrayMin(int[] arr, int[] secondArr) {
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
for (int i = 0; i < secondArr.length; i++) {
if (secondArr[i] < minValue)
{
minValue = secondArr[i];
}
}
System.out.println(minValue);
return minValue;
}
}
As a final concern, in your code, you return minValue before you try to print the result, so the print instruction is always unreachable.