For my program, i am making a 2D jagged array of integers and the length of each array inside depends on the input of the user.
Lets say for something like:
int seq [] [] = new int [M] [];
for(int i = 0; i < M; i++){
seq[i] = new int [N[i]];
The total number of arrays (M) and the N array with length for each array depends on the input by user.
Is there a way i can make this so the resultant 2D array can be used by any method inside the class?
Thanks.
You can make it array an instance variable and initialize it in some init method or constructor.
public class Test{
int[][] array;
public void initialize() {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
array = new int[m][n];
}
public void processArray() {
if(array != null) {
//process array
}
}
}
Yes it is Possible you Take The Size of the Rows and Columns of the Array at run time then Create the Array According to the Size you Provide.
int m;
int n;
System.out.println("EnTer size of Row and column");
m = input.nextInt();
n = input.nextInt();
int[] arr = new int[m][n];
Related
Sample with input and outputsI'm trying to apply the divide and conquer theorem on an array of integers in which I am to find the worst case index. On the initial array I have to split it into two on both sides of the midpoint. This is repeatedly done and at each instance the midpoint is deleted. I am to check for the peak on each sub array but in the end I am to print out only the indexes of all the worst cases. In as the input will be the initial length of the array at any given instance. So far I have been able to request and input and print out an array of indices of a given length n. Given that I'm not too familiar with Java yet I don't know how to go about it.
class Peak {
public static void main(String a[]){
List<Integer> al = new ArrayList<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("enter the length of the array: ");
int n = s.nextInt();
for (int i = 0; i < n ; i++)
al.add(i);
System.out.println(al);
int size = al.size();
if (al.size()%2==0) {
//Sublist to ArrayList
ArrayList<Integer> lhs = new ArrayList<Integer>(al.subList(0, (size - 1)/2));
ArrayList<Integer> rhs = new ArrayList<>(al.subList((size + 1)/2, n));
}
if (al.size()%2==1) {
//Sublist to ArrayList
ArrayList<Integer> lhs = new ArrayList<Integer>(al.subList(0, (size - 1)/2));
ArrayList<Integer> rhs = new ArrayList<>(al.subList((size + 1)/2, n));
}
}
I need to write a program which should read a few numbers from an int, then save the values in array and to calculate the modulo of the numbers I read in.
I made this so far, but I have no idea how to store int in array, or how to calculate modulo of an array. Hope someone can help.
public class modulo {
public static void main (String[] args) {
int counter = 0;
int r = 0;
int modus;
int numbers;
int[] n;
Out.print("How many numbers you want to calculate: ");
r = In.readInt ();
Out.print("With which number you want to calculate the modulo: ");
modus = In.readInt ();
while (counter != r) {
counter++;
Out.print("Put the " + counter + ".number: ");
numbers = In.readInt ();
}
First of all, you need to new your array, otherwise you'd get NullPointerException. Since you already know your array size, this is what you will write after you've read r from the input:
int[] n = new n[r]
Then, you need a for loop to read from the input and save it to the array.
As for your next question, here is the answer.
How can I implement a modulus on a list of numbers?
Arrays are not dynamic, meaning, once given a size it will stay that size. For example "int[] arr = {1, 2, 3, 4, 5, 6}; or int[] arr = new int[5];"
For this particular example you may want to do the second declaration of array that I gave you as an example because this allows you to later declare the size of the array(after you get your input from how many numbers you want to calculate"
after this you ask with which number you want to calculate the array to. This can be done using a for loop and then doing something like:
for(int i = 0; i < arr.lenght; i++){
new_arr[i]= arr[i]%mod; //this stores each operation into a new array.
}
hope this helps!
I do this, still the same
public class modulo {
public static void main (String[] args) {
int counter = 0;
int zahlen = 0;
int modus;
int numbers;
int[] n = new int[zahlen];
int [] new_arr = new int [0];
Out.print("Wie viele Zahlen moechten Sie berechnen: ");
zahlen = In.readInt ();
Out.print("Mit welcher Zahl moechten Sie Modulo berechnen: ");
modus = In.readInt ();
while (counter != zahlen) {
counter++;
Out.print("Geben sie die " + counter + ".Zahl ein: ");
numbers = In.readInt ();
}
for(int i = 0; i < n.length; i++){
new_arr[i]= n[i]%modus;
Out.print(new_arr);
}
}
}
I have researched and tried for hours to solve my problem, but the reality is that I can't find anything on it. It is simple really. I need to initialize java arrays of undefined size, and then compare the two. In the process of testing my program, when I have defined the array to a specific length (for example)
int[] array = new int[6];
the code waits until I have entered the six objects to move on to the next segment of code, because it is waiting for 6 integers as defined as the array length. But I can't define the array using
int[] array = {};
it obviously won't work, since array.length function will be 0.
My code is below.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// My problem is in the definition of the arrays or the for loops defining them below.
int[] list1 = new int[]; // undefined
int[] list2 = new int[]; // undefined
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I need to initialize java arrays of undefined size,
You need to use an ArrayList or ask the length at the start.
List<Integer> list1 = new ArrayList<>();
System.out.println("Enter numbers, with a blank line to end");
for (String line; !(line = input.nextLine()).trim().isEmpty(); ) {
list1.add(Integer.parseInt(line));
}
// later
if (list1.equals(list2))
or use an array
System.out.println("Enter the number of numbers, followed by the numbers");
int[] array1 = new int[input.nextInt()]; // enter the size first.
for (int i = 0; i < array1.length; i++)
array[i] = input.nextInt();
// later
if (Arrays.equals(array1, array2))
int[] array = {};
it obviously won't work, since array.length function cannot work.
This works as expected and array.length is always 0
I am still unable to fulfill what I am really trying to accomplish, but I've used my code to compromise. It is to allow the user to specify the length before entering integers.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many variables long is the first list? ");
int n = input.nextInt();
int[] list1 = new int[n];
System.out.print("How many variables long is the second list? ");
n = input.nextInt();
int[] list2 = new int[n];
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I see that this question is an older one but I had the same one (or at least similar) and couldn't find answer I was searching for. And now I believe I have the answer for this and would like to share it. Maybe for someone this will be handy.
According to my understanding the question is about creating a single dimensional array with undefined length and the length of this array is going to be increased by the Scanner input. Lot of answers I have seen were about using the ArrayList. But still I wanted to know how to do it with a single dimensional array. First, let me share with you the code and then the explanation:
public class Main {
static Scanner scanner = new Scanner(System.in);
final static int ARRAY_MAX_LENGTH = 400_000_000;
public static void main(String[] args) {
int[] numbers = createIntArray();
displayArray(numbers);
}
public static int[] createIntArray() {
int[] ints = new int[ARRAY_MAX_LENGTH];
System.out.print("Enter numbers: ");
for (int i = 0; i < ints.length; i++) {
ints[i] = scanner.nextInt();
if (ints[i] == 0) {
break;
}
} return ints;
}
public static void displayArray(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
if (ints[i] == 0) {
break;
}
}
}
}
Now the explanation:
We want undefined/infinite array length. The truth is: you can not have it. In programming everything has limit. The byte limit is between -128 to 127 the short limit is -32,768 to 32,767 and the int limit is between -2,147,483,648 to 2,147,483,647. So how do you create array with undefined length? Paradoxically: set the array length. And the length should be the maximum length an array can hold. And then create an exit point when you want the array to accept no more inputs from the Scanner class. I solved it by including in my code the if statement with a break keyword (if(input == 0) break;). Once I do not want to make any input with the Scanner class I just type '0' and press enter and the array does not accept any other input and the inputs made before the '0' is saved int the defined int[] numbers array.
Now coming back to the array max length... I found articles that the array max length is the int max length minus 8 (or something similar). This didn't work for me. I read some posts here on Stack Overflow that the array length depends on the JVM and on other factors I have not explored further. I thing the max array length depends on some settings too but I don't want to lie. This is why I set my array length to 400 000 000. When I set the length to 500 000 000 I got the error:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
If you want to use this code just figure out what is your max array length and use it.
For me this problem was interesting to think about but definitely I would not use it in big programs. It is not efficient at all. For newbies: if you have just learned the one dimensional array, be patient, ArrayList is coming in your later studies and it could make things easier.
I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended
i want to create an array of 5 indexes, which will have an index with another whole array in each one. each array within the 5 index will need to be as many indexes as follows (10, 100,1000,10000) but i dont know how to fill an array like this inside of my for loop ,that is typically used with an array, without it running into infinity, because where i have
for(int x = 0; x < array.length; x++),
i cant use the x variable in here;
int[x<--(syntax error)] array = {ten = new int[arraySize], hundred = new int[arraySize], thousand = new int[arraySize], tenthousand = new int[arraySize],
without it telling me there is a syntax error . i don't know what to do.
all this code is part of a method of its own class as well if that helps understand better.
public int ArrayArray(int arraySize, int randomNumber) {
arraySizes = arraySize;
for(int x = 0; x < array.length; x++) {
size = 0;
Random gen = new Random(randomNumber);
int[]ten;
ten = new int[arraySize];
int[] hundred;
hundred = new int[arraySize];
int[]thousand;
thousand = new int[arraySize];
int[]tenThousand;
tenThousand = new int[arraySize];
int[] array = {ten[x] = gen.nextInt(10), hundred[x] = gen.nextInt(100),
thousand[x] = gen.nextInt(1000), tenThousand[x] = gen.nextInt(10000)};
return array[];
}
this changes my question a little i think ive got it after having worked on it. does this look like it will return what i want it to do? im going to have a driver that i will call this method with a given array size and a given number of random integers.
If you are trying to return and array your function try this:
public int[][] ArrayArray(int arraySize, int randomNumber) {
Random gen = new Random(randomNumber);
int[]ten= new int[10];
int[] hundred= new int[100];
int[]thousand= new int[1000];
int[]tenThousand= new int[10000];
int[][] array = {ten,hundred,thousand,tenthousand};
return array;
}
notice it is int[][] and not int[]. this is because the array you are trying to return a two dimensional array not just a single dimensional array.
let me know how this works.
If you are trying to create array of arrays then multi dimensional array is the way to go.
int arraySize = 10;
int[]ten = new int[arraySize];
int[] hundred = new int[arraySize];
int[]thousand = new int[arraySize];
int[]tenThousand = new int[arraySize];
int[][] array = new int[4][arraySize];
array[0] = ten;
array[1] = hundred;
array[2] = thousand;
array[3] = tenThousand;
Also passing around a 2-dimensional array is same as arrays. Eg.
public static int hello(int[][] pass) {
return pass;
}