Error with index of an array in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem โ€” and include valid code to reproduce it โ€” in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Why it doesn't work?
P.S. I am beginner in Java.
int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
userInfo["result"] = userInfo[0] + userInfo[1];
System.out.println(userInfo["result"]);

Only an int can be an index into an array. A String won't work. If you need 3 slots, declare your array to be length 3 and then you can use userInfo[2].
The JLS, Section 10.4 makes it pretty clear:
Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (ยง5.6.1) and become int values.

int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
int result = userInfo[0] + userInfo[1];
System.out.println(result);
The string can not be the index in array.

Your array has 2 slots, and you used them to store the numbers. To get the sum, do this:
int sum = userInfo[0] + userInfo[1];
Also, even if your array had a third slot, you can only access individual elements by their numerical index (0, 1, or 2 in this case). Not by a String like result.

In java, arrays only have zero and positive integer indexes. This means that an array can only be accessed with 0 to size of the array minus 1.
If you want to do something like:
userInfo["result"] = userInfo[0] + userInfo[1];
You can try the following:
int result = userInfo[0] + userInfo[1];
System.out.println(result);
or:
Map<String,Intgeer> example = new HashMap<String,Intgeer>();
example.put("result", new Integer(userInfo[0] + userInfo[1]));
System.out.println(example.get("result"));

There are several problems here as I mentioned in comments. You declare an array of int here:
int userInfo[];
Then try to pass a string into it here (that won't work):
userInfo["result"]; // This is bad news
Your cleaned-up code should look like this:
int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
int sumArrayValues = userInfo[0] + userInfo[1];
System.out.println(sumArrayValues);
Happy coding!

Related

How to return and call a Dynamic 1D Array from a method in java? (What am I missing in my code)? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
public static int createArray(int theListSize)
{
ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
for (int i=0; i<=theListSize; i++) //simply creates the array
{
possiblePrimeNum.add(i, i+2);
}
return possiblePrimeNum;
}
I don't understand this code. I mean that I understand what I'm going to do, but I don't know why the array won't return. What's wrong here?
possiblePrimeNum=createArray(theListSize);
You declared this method as returning a single int value, a single number, and a primitive (not an object).
An ArrayList is a collection of numbers, Integer objects (not primitives).
You said:
Dynamic 1D Array
I do not know what you mean by "Dynamic".
An array in Java is not the same as an ArrayList. The first is a built-in basic type in Java. The second is a class found in the Java Collections Framework, bundled with all Java distributions.
Tutorial on arrays by Oracle
Tutorial on Collections by Oracle
You asked:
I mean that I understand what I'm going to do, but I don't know why the array won't return.
Change your method to return a List of Integer objects rather than a single int. Something like this.
public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
for ( int i = 0 ; i <= countOfPrimes ; i++ )
{
possiblePrimes.add( i , i + 2 );
}
return List.copyOf( possiblePrimes ); // Return a unmodifiable list, as a general best practice.
}
Call that method like this.
List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " + maybePrimes );
When run:
maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]
I think your algorithm for finding candidate primes needs some more work. ๐Ÿ˜ตโ€๐Ÿ’ซ
If you really want an array, see:
How to convert an ArrayList containing Integers to primitive int array?
Convert ArrayList of Integer Objects to an int array?

Initializing an int variable as in between 2 values in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm totally new to Java, and I'm facing a little problem. Sometimes I need to declare a numerical variable in between two values like int x>=2 && x<=20; but I can't find a way to do that.
For example I have this problem to solve:
Given an integer, N, print its first 10 multiples. Each multiple N*i (where 1 <= i <= 10) should be printed on a new line in the form: N x i = result.
Constraints
2 <= N <= 20
How can i solve that, and how can I initialize an int variable "in between two values" ?
It makes no sense to "initialize a variable between 2 values", as a variable can have only 1 value at a time.
You should give the different possible values to the variable one by one :
int i=1;
while(i<=10){
System.out.println("N x " + i + " = " + (N*i));
i++;
}
Final result
If you don't want to keep your i variable after you can use a for loop:
for(int i=1; i<= 10; i++){
System.out.println("N x "+ i +" = " + (N*i));
}
You can do the same if you want to do this for all the specified values of N:
for(int N = 2; N <= 20; N++)
for(int i = 1; i <= 10; i++)
System.out.println("N x "+ i +" = " + (N*i));
About variables with several values
In software programming, the very concept of a variable is a "placeholder to store a value". So by definition, a variable can hold only one value, and is doing so at any time.
When you see variables that seem to hold several values, they are actually holding 1 value, which itself is a container for several values.
It is not possible to give an int variable a range as its value. However, it is possible to change the value of an int at runtime.
For the given problem, there are two approaches I might consider using.
Taking a command line argument
You can write your program to take a value given on the command line and assign it to your int variable. Assuming you are within your main method, command line arguments are kept in the args array and can be accessed like this...
int value = Integer.parseInt(args[0]);
This will store the first argument given on the command line in the variable value, provided it is parseable as an integer. So if you run the program with the command java Program 10, then value will be assigned value 10.
Asking the user for input
Look up the Scanner class and use it to ask the user for a value in the range that you want.
Like this...
Scanner in = new Scanner(System.in);
int value = in.nextInt();
Obviously if you want to make sure that the given values lie in your desired range this can also be checked at runtime pretty easily.
Java doesn't allow to specify range of variable like python's range(int,int) method . However you can use Range class from apache commons library.
For your problem, there is no need to declare variables value beforehand. Just initialize the variable with the lowest value ,perform some calculation and increment the variable in a loop.
public static void main(String[] args){
int n = 2;
while(n<=20){
for(int i=1;i<=10;i++){
System.out.println(n+"X"+i+"="+n*i);
}
n=n+1;
}
}

How to add two or more numbers and display the sum (Netbeans) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So i'm a beginner and I am trying to figure out how to add more than 2 numbers and display it through the output of netbeans. Its really confusing for me since i'm still new to programming.
First, you need to define variable.
what is variable?
A variable provides us with named storage that our programs can
manipulate.
There are different type variable in Java like int, double, char, String, and so on.
What do I mean by type variable?
determines the size and layout of the variable's memory
he range of values that can be stored within that memory
the set of operations that can be applied to the variable
How to define Variable in Java
data type variable [ = value][, variable [= value] ...] ;
For example , you can define two variable as int type as follows
int firstNumber = 1;
int secondNumber = 2;
Note if you like you can define more than two variables by following up the rules.
you can do Arithmetic Operators on your variables
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Here you want to add so you need to use + operator.
read this which is my source : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
At the end, you should define a variable that carries the summation of two variables like
int sum = number1 + number2;
and print the value on your console by using System.out.print/ln
System.out.print("the summation of number one and number two is " + sum);
Source:
http://www.homeandlearn.co.uk/java/java_int_variables.html
http://www.tutorialspoint.com/java/java_variable_types.htm
int a = 1;
int b = 2;
int c = 3;
int d = a + b + c;
System.out.println(d);
If you want to add up the numbers in an array or collection:
int[] numbers = { 1, 2, 3 };
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(sum);

Finding the largest number in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to figure how to find the largest number in an array of random numbers.
So far I cant manage to get it right.
Its an array[50] and the random, numbers are between 0-100.
Thanks!
Loop through the array and keep track of the largest number found already in an int variable.
public int findMax(int[] numbers)
{
int max = 0;
for (int i = 0; i < numbers.length; ++i)
if (numbers[i] > max) max = numbers[i];
return max;
}
(You can also initialize max to int.MIN_VALUE or something if it helps behave more suitably in the case where an empty array is passed in.)
Use:
java.utils.Arrays.sort(yours_array);
int largest = yours_array[yours_array.length - 1] ;
Collections.max and you can use it as follows with a raw array:
List<Integer> triedArray = new ArrayList<Integer>();
ArrayUtils.addAll(intArray);
This does add a dependency on commons-lang, though.
Assuming the int[] is named array
Try to use a loop like the following:
int biggest = array[0]
for(int a = 1; a < array.length; a++){
if(array[a] > biggest){
biggest = array[a]
}
}
At the end, your variable biggest will hold the largest value in the array.

Store repeating sequence of integer in another array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have two arrays a[] and b[].
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
Array length in actual problem can change.
The values in the array must be less then value of array length as seen.
The output must be:
b = 3 1 0 0 7 4 6 0 3 1
So basically if there is a sequence of same value in a[] then only 1st of its value must be placed at same index in b[] rest should be zero till the sequence exists.
Answer in java syntax will be helpful.
Thank you in advance
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
int temp = a[0];
b[0] = temp;
for(int i = 1; i < a.length; i++) {
if(a[i] == temp)
b[i] = 0;
else
b[i] = a[i];
temp = a[i];
}
hint:
1) create hashmap to store processed values
2) iterate over the first array: if current value is stored in map, then fill 0, otherwise store this value in HashMap and copy the value to new array

Categories