I'm declaring a 2d Array with 100 rows and columns. Im trying to get the user to dictate the numbers that go into the array. Im supposed to store the values without storing them in a variable. This is what I have so far but I don't think this is correct
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] nums = new int[100][100];
int digits;
for (int i = 0; i < nums.length; ++i)
{
int[scan.nextInt()][scan.nextInt()];
}
You'll need to use nested for loops for a 2-d array (one for rows and one for columns):
for (int i = 0; i < nums.length; ++i)
for (int j = 0; j < nums[i].length; ++j)
{
nums[i][j] = scan.nextInt();
}
Well, first of all, you are dealing with a two dimensional array, so you will need two loops, one for the rows and the other for the colums.
for(int i=0; i<100; i++)
{
for(int j=0;j<100;j++)
{
nums[i][j] = scan.nextInt();
}
}
This syntax - int[scan.nextInt()][scan.nextInt()]; is not even legal.
Related
I'm looking to create a dynamic amount of arrays of random integers and then put them into an array list. Later I want to use each of these arrays separately to test for quick sort functionality. I'm having problems with adding the object List[] into the ArrayList.
//Create dynamic amount of random arrays
public static ArrayList<int[]> Randomizer(int arrays, int size, int seed){
ArrayList<int[]> Tests = new ArrayList<int[]>(arrays);
int[] List = new int[size];
for (int j = 0; j < arrays; j++){
Random r = new Random(seed+j);
for(int i = 0; i < size; i++){
List[i] = r.nextInt(5*size);//Multiplier for how big the numbers get
System.out.print(List[i] + ",");
}
System.out.println();
Tests.add(j, List);
}
return Tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> Test = Randomizer(tests,size,10); //1st = Number of Tests
//2nd = Number of Digits
//3rd = seed for Randomizer
for(int i = 0; i < Test.size(); i++){
System.out.println(Test.get(i));
}
}
}
The problem with your code was that you were storing the same array 5 times into the ArrayList, so when printing during generation it printed correct numbers, but later you couldn't get them out. Each iteration of the for loop was overwriting the values generated earlier.
Here is the corrected code:
private static ArrayList<int[]> randomizer(int arrays, int size, int seed){
ArrayList<int[]> tests = new ArrayList<>(arrays);
for (int j = 0; j < arrays; j++) {
int[] list = new int[size];
Random r = new Random(seed + j);
for(int i = 0; i < size; i++) {
list[i] = r.nextInt(5 * size); // Multiplier for how big the numbers get
}
tests.add(j, list);
}
return tests;
}
public static void main(String[] args) {
int tests = 5;
int size = 4;
ArrayList<int[]> arrays = randomizer(tests, size, 10);
for (int i = 0; i < arrays.size(); i++){
int[] ints = arrays.get(i);
for (int j = 0; j < ints.length; j++) {
System.out.print(ints[j] + ",");
}
System.out.println();
}
}
Basically you needed to move the int[] list = new int[size]; line inside the for loop, so that you are actually creating new arrays instead of using the same one each time.
You can now replace the printing loop in the main() method with whatever you like, like your quick sort tests. Let me know if anything still doesn't work.
I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)
The user will type in the number for i (variant), then the number for j (elements for every variant), and finally the maximum value possible (maxElem).
Using the inputed values, the task is to generate nonrepeating random numbers (nonrepeating in a variant, meaning for i, but the numbers may repeat during the entire array).
For example, a successful output giving the input 3 (i), 5 (j), 9 (maxElem), would be:
4|8|1|7|9
3|8|2|4|5
2|6|4|8|5
As you may notice, the number 4 repeats itself during the entire array for 3 times (allowable). But, for i=0, number 4 is unique.
Please, guide me what would be the changes to this code:
static Scanner sc = new Scanner(System.in);
static int maxElem;
public static void main(String[] args) {
int[][] greatLoto;
System.out.println("Of how many variants will the ticket consist? ");
int variants = sc.nextInt();
System.out.println("Of how many elements will the variants consist? ");
int elements = sc.nextInt();
System.out.println("Which value should be considered the maximum value? ");
maxElem = sc.nextInt() + 1;
greatLoto = new int[variants][elements];
System.out.println("Initial values: ");
show(greatLoto);
System.out.println("Modifying values...");
modified(greatLoto);
System.out.println("Newest values: ");
show(greatLoto);
}
private static void show(int[][] greatLoto) {
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
System.out.print("|" + greatLoto[i][j] + "|");
}
System.out.println("");
}
System.out.println("");
}
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
while (Arrays.asList(greatLoto[i]).contains(r)) {
r = new Random(System.currentTimeMillis());
}
greatLoto[i][j] = r.nextInt(maxElem);;
}
System.out.println("");
}
}
This is more of a comment but too long: don't use random.next() because it forces you to check for uniqueness. Instead fill a list with the valid values and shuffle it:
List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);
Then you can simply iterate over the values and take the j first numbers.
Note that if j is significantly greater than i using the random approach would probably be more efficient.
The most minimal change would be:
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
do {
greatLoto[i][j] = r.nextInt(maxElem);
} while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));
}
System.out.println("");
}
}
But there are more elegant (but difficult to code) ways to generate unique random numbers without discarding duplicates.
You need three loops:
Loop_1: Builds an array of size j and uses Loop_1B for every field of this array.
Loop_1B: Generate an int with r.nextInt(maxElem)+1; (it has to be +1 because nextInt() is covering the 0 inclusively and the specified value exclusively). Afterwards check if the number is already used in the array, if yes, run this loop again.
Loop_2: Repeats Loop_1 i times.
I've got a program where the user is giving the program the size of the array ie(the column and row size) and I am trying to give every position in the array the same value. I'm having an issue with my loop though, here it is.
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
I can see that the issue is I am trying to give a value to a position that doesn't exist but I have no idea how to work around this issue. Any help would be appreciated :)
Try working with length, not with user input:
// ask user for sizes
int col = ...;
int row = ...;
// declare the array, let it be of type int
// it's the last occurence of "row" and "col"
int[][] data = new int[row][col];
// loop the array
for (int r = 0; r < data.length; ++r) { // <- not "row"!
int[] line = data[r];
for (int c = 0; c < line.length; ++c) { // <- not "col"!
// do what you want with line[c], e.g.
// line[c] = 7; // <- sets all array's items to 7
}
}
working with actual array's dimensions just prevent you from accessing non-existing items
From the code snippet you provided it seems you are fine. Maybe the array is not well initialized or you mismatched the row and column numbers. Try to use more specific variable names than 'i' and 'j'.
in java
try{
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
}catch(IndexOutOfBoundsException exp){
System.out.printlv(exp.getMessage());
}
To begin, what makes you say that you "can see that the issue is I am trying to give a value to a position that doesn't exist"? What symptoms are you seeing that makes you believe this?
On the face of it, your code looks fine, however (and this is a big however) you have omitted the most important bits of code, viz the declaration of your 2D array, and the part inside the loop body where you assign the value to the array member. If you add these then I, or somebody else, may be able to help further.
Solution:
int matriz[][] = new int [row][col];
for(int i = 0; i <row; i++){
for(int j = 0; j < col; j++){
matriz[i][j] = 0;
}
}
//try this one
import java.util.Scanner; //Scanner class required for user input.
class xyz
{
public static void main(String ar[])
{
int row,col;
Scanner in=new Scanner(System.in); //defining Object for scanner class
System.out.println("Enter row");
row=in.nextInt();
System.out.println("Enter Column");
col=in.nextInt();
int mat[][]=new int[row][col]; //giving matrix size
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
mat[i][j]=0; //or any value decided by you
}
}
}
}
My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}