cl.waller
cl.waller

Reputation: 3

Saving a value into a 2D array

I'm trying to set up an array where I can save a value into the 2D array so I can use it later for calculations. I have set up the array however when I go to save the value it changes the value into the value of the array position E.g. array[0][0] changes my value to 0 ( not what I'm after) how do I fix this?

This is my code:

import java.util. *;
import java.util.ArrayList;
public class project {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[][] register = new int [10][10];
    int x=0;
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
        {
            register[i][j]=x;
            x++;
        }
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
            System.out.print(register[i][j] + " ");
        }
        System.out.println();
}

    Scanner kb = new Scanner(System.in);
    System.out.println("Enter number" );
    int a = kb.nextInt();

    a = register[0][0];


    System.out.println("Enter another number" );
    int b = kb.nextInt();

    System.out.println( a-b );

This is the output:

0 1 2 3 4 5 6 7 8 9 
10 11 12 13 14 15 16 17 18 19 
20 21 22 23 24 25 26 27 28 29 
30 31 32 33 34 35 36 37 38 39 
40 41 42 43 44 45 46 47 48 49 
50 51 52 53 54 55 56 57 58 59 
60 61 62 63 64 65 66 67 68 69 
70 71 72 73 74 75 76 77 78 79 
80 81 82 83 84 85 86 87 88 89 
90 91 92 93 94 95 96 97 98 99 
Enter number
8
Enter another number
5
-5

Upvotes: 0

Views: 224

Answers (1)

Sandip Ghosh
Sandip Ghosh

Reputation: 719

You have replaced the value of a with the first value in the matrix in the line a = register[0][0] Looks like a silly mistake

From what you are saying, I get that what you wanted to do was the opposite may be. Like register[0][0] = a

Upvotes: 1

Related Questions