Array is being changed when in for statement - java

I think that it supposed to be posted with entire codes in this time.
When I'm trying to get values from Scanner into array named "score",
the second for statement shows unexpected outcomes.
import java.util.Scanner;
public class B1546 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] score = new int[N];
Max scoreMax = new Max();
double sum = 0;
for (int i=0; i<N; i++) {
score[i] = input.nextInt();
}
for (int i=0; i<N; i++) {
System.out.println(score[i]); // this show the problems
sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
}
System.out.println(sum / N);
}
}
class Max {
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
for( int i=0; i<score.length-1; i++) {
for( int j=i+1; j<score.length; j++) {
if (tmpArray[i]<tmpArray[j]) {
int tmp = tmpArray[i];
tmpArray[i] = tmpArray[j];
tmpArray[j] = tmp;
}
}
}
return tmpArray[0];
}
}
For example, when I type
3
10 20 30
then It comes
10
20
10
...
not
10
20
30
...
I don't know what is the problem.

Your Max.max method changes the array - the 3 lines starting with int tmp =.
Likely the source of your problems is not understanding reference types. tmpArray = score does not make a separate copy of the array score -- you just have two references to the same array. This concept is fundamental to Java programming.

int max (int[] score) {
int[] tmpArray;
tmpArray = score;
}
score is a reference to the array object. Here you create a new reference to the existed array. To fix it, jut make a new array object:
int max(int[] score) {
int[] tmpArray = Arrays.copyOf(score, score.length);
}

int[] are objects and therefore are passed-by-reference in Java. When you do the following in your Max#max(int[]) method:
int[] tmpArray;
tmpArray = score;
Both tmpArray and score will hold the same reference, so when you swap values in the tmpArray, the score-array will be modified as well.
You'll have to create a new integer-array instead for the tmpArray, and copy the values. The simplest would be one of the following two:
int[] tmpArray = score.clone();
// or:
int[] tmpArray = Arrays.copyOf(score, score.length);
I would suggest the second, the .clone() is normally used for other purposes.
Try it online.

Related

How to use create 2 Array with User input with Std.readAllInts()

This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.

How to use previous parameter from array in for loop

I have been try to code this, to increment the user input by 33 if the input is "31" or more up to the input or "90", and I have hit a wall where I want to use the user input from the array but I cannot. Could anyone help? Thank you.
if (choice.equals("R")) {
System.out.println("You have selected to draw a Rectangle!");
System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");
int[] array = new int[2];
int[] array2 = new int[2];
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
String[] numbers1 = line1.split(" ");
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
I am trying to make a method to be able to easily call upon it later on, but that's the problem as I cannot complete my calculation.
public static void timeTurn (int a, int b) {
for(int i = 1000; i < 3001; i+= 33) {
if(numbers1.equals(>=30)) {
}
}
}
int[] array2 = new int[2]; is useless here.
By the way, please do not name a variable "array" or "array2". It's hard to understand for others and for yourself in the future.
if you defined the "array"s length to 2, then this for loop for(int i=0;i<numbers1.length;i++){...} is meaningless cause you already defined that you can only have two integers in this array.
I do not know the meaning of "convert cm to milliseconds" since one is distance and the other is time...
I can not understand (int a, int b) what "a", "b" means.
by my understanding the second code should be:
public static void timeTurn (int[] length) {
int minMillsecond = 1000;
int maxMillsecond = 3001;
int gap = 33;
for(int len : length){
if (30 <= len <= 90){
len += minMillsecond;
while(len < 3000){ len+=gap;}
print len;
}
}
}

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

Array with matrices table in Java

int [] arr = {-1,1,1,1,1}
int [] num = {23,24,25,26}
If I just want to sum {24,25,26}, how to call from arr[1,1,1,1}? For example: num 23 in index 0 of arr, num 24 in index 1 of arr and so on.
for (//..........) {
System.out.print (//.....)
}
Please note: array in arr is a table only. It does not mean summing, like a matrices table.
Here is the code I have come up with, you will need a method.
public int sum(int[] matrix, int ... args)
{
int sum = 0;
for(int index : args)
{
sum += matrix[index];
}
return sum;
}
This would basically take the matrix, then based upon any number of other arguments you gave, take the indexes and sum the values.
This will add the second array to the first, and ignore any items that are on indexes larger than the first array (for instance, if first array is {3, 4} and the second is {5, 3, 4} the 4 in the second array will be ignored).
private void sumArrays(int[] first, int[] second){
for(int i = 0; i < first.length; i++){
if(i >= second.length){
break;
}
first[i] += second[i];
}
}
If you are looking for the sum of your num array elements beginning from a parameter index then try this:
int [] num = {23,24,25,26};
public int CalculateSum(int index)
{
int sum =0;
if(index<num.length)
{
for(int i=index;i<num.length;i++) {
sum+=num[i];
}
}
return sum;
}

Removing specific value from array (java)

i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}

Categories