I am trying to find the sum of the integers in an ArrayList, however I am having issues with data types.
Here is the code I have at the moment:
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
sum = sum + InputArray.get(i)
}
However this is giving me the error:
error: bad operand types for binary operator '+'
I have also tried:
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
int foo = Integer.parseInt(InputArray.get(i));
sum = sum + foo;
}
However this is giving me the error:
error: no suitable method found for parseInt(object)
The ArrayList contains integers only.
What could be the problem?
ArrayList InputArray = new ArrayList(); is what I declared it as
Elements of collections that use raw types need to be cast to access the methods of the reference types. Generics were introduced to avoid this. Replace
ArrayList InputArray = new ArrayList();
with
List<Integer> inputArray = new ArrayList<>();
//If your list should only Integers, there's no reason not to do this
ArrayList<Integer> InputArray = new ArrayList<Integer>();
//Add some integers
InputArray.add(1);
InputArray.add(2);
InputArray.add(100);
//Create your sum variable
int sum = 0;
//You could use a foreach loop
for(int i : InputArray) {
sum += i;
}
You have to define the type of your ArrayList;
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i=0; i < 10; i++) {
a.add(i);
}
int sum = 0;
for (int i=0; i < 10; i++) {
sum = sum + a.get(i);
}
System.out.println(sum);
First you need to make sure that the ArrayList is created the correct way with the desired type:
ArrayList<Integer> list = new ArrayList<Integer>();
Then you can make a loop:
int sum = 0;
for (int i=0; i<list.size(); i++
{
sum += list.get(i);
}
System.out.println(sum);
Try this. Good luck!
Here is a working code using an input array of strings as you should have strings as input from user (from input.nextLine):
import java.util.ArrayList;
import java.util.List;
public class Sum {
public static void main(String[] args) {
List<String> InputArray = new ArrayList<String>();
InputArray.add("1");
InputArray.add("2");
int sum = 0;
for(String element : InputArray) {
sum += Integer.valueOf(element);
}
System.out.println(sum);
}
}
Try this instead.
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
int foo = Integer.parseInt(InputArray.get(i).toString());
sum = sum + foo;
}
The reason it doesn't work is because you're trying to parse an int from something that's not a String.
By adding the .toString() method, you'll get around this.
Related
I'm using Java to implement the Bucket Sorting. I want to sort the input array of [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434] and I create the buckets as an array containing List<Double> as it's elements, I sort every List<Double> individually using List.sort and concatenate them to get the result.
But Error occurs when I use the ArrayList.sort method to sort the List. I use a Lambda Expression as the parameter of the sort function and get an error message from the IDE, it says Cannot infer functional interface type .
The error comes from this line:
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
But when I change it to
buckets[i].sort((a, b) -> (int)Math.signum(a-b));
there is no error and the code works well.
I am very confused why it can't infer? Thanks in advance.
The entire code is here:
import java.util.ArrayList;
import java.util.List;
class Solution {
void buckerSort(double[] arr, int n){
//create the buckets
List<Double>[] buckets = new ArrayList[n];
for (int i = 0; i<n; ++i){
buckets[i] = new ArrayList<Double>();
}
//add the input to the buckets
for (int i=0; i<n; ++i) {
int index = (int) arr[i] * 10;
buckets[index].add(arr[i]);
}
//sort every List individually
///////////////////////////////The error occurs here/////////////////////////////////////////
for (int i=0; i<n; ++i) {
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
}
//concatenate
int index = 0;
for(int i = 0; i<n; i++) {
for (int j = 0; j<buckets[i].size(); j++) {
arr[index] = buckets[i].get(j);
index++;
}
}
}
public static void main(String args[])
{
double[] arr = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = arr.length;
Solution s = new Solution();
s.buckerSort(arr, n);
System.out.println("Sorted array is: ");
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
}
}
}
You can use
buckets[i].sort( ( Double a, Double b ) -> (int) Math.signum( a - b ) );
instead, since a Comparator of Double accepts two Double type arguments and not primitive double arguments.
public int compare( Double a, Double b )
More importantly, you might just be looking to sort the elements naturally using Comparator.naturalOrder() as performing a subtraction isn't a good way of comparing elements. So your code would look like -
buckets[i].sort( Comparator.naturalOrder() );
I have two lists of elements and numbers but how can I put them into arrays if I don't know the exact array size? new int[elements.size()][I'm not sure about this size].
For example:
List of elements = [2,5]
List of numbers = [99,100], [1,9,8,10,70]
public static int[][] arrays(List<Integer> numbers, List<Integer> elements){
int count = 0;
int x = 0;
int y = 0;
int[][] list = new int[elements.size()][];
for (Integer e : elements) {
for (int i = count; i < count+e; i++) {
list[x][y] = numbers.get(i);
y++;
}
x++;
y = 0;
count += e;
}
return list;
}
The correct input for your method would be a list of lists, with each list in the parent list potentially having a different length:
public static int[][] arrays(List<List<Integer>> numbers) {
int[][] array = new int[numbers.size()][];
for (int i=0; i < numbers.size(); ++i) {
array[i] = new int[numbers.get(i).size()];
for (int j=0; j < numbers.get(i).size(); ++j) {
array[i][j] = numbers.get(i).get(j);
}
}
return array;
}
I have this question that I have been tackling for a while.
"The method should return an array containing the elements that are divisible by a certain number" in this case the target which is 5.
Here is my solution
public static int[] Divisible(int[] array, int target){
int[] answer = new int[array.length];
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer[i] = array[i];
}
}
return answer;
}
assuming my input is
int[] input = {5,3,6,10};
my output will be [5,0,0,10].
My desired output should be [5,10].
please, How do I get rid of the zeros
The basic idea is to fill the answer array from the bottom, and then truncate it to exactly the size you need.
int j = 0;
for (int i=0; i<array.length; i++) {
if (array[i] % target == 0){
answer[j++] = array[i];
}
}
return Arrays.copyOf(answer, j);
Arrays is a standard Java utility class.
If you're not allowed to use the Arrays utility class then the last line can be replaced by:
int[] answer2 = new int[j];
for (int i=0; i<j; i++)
answer2[i] = answer[i];
return answer2;
This feels a little clunky to me but it satisfies the apparent requirements to use simple arrays.
you can do like this
public static int[] Divisible(int[] array, int target){
List<Integer> list = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
list.add(array[i]);
}
}
int[] ints = new int[list.size()];
for (int i = 0; i < ints.length; i++) {
ints[i] = list.get(i);
}
return ints;
}
Two options:
you can use an ArrayList internally, as that can grow dynamically (you just keep adding the values you are interested in, done). If you have to return an array, you can easily do that based on your filled list.
when going only with arrays you can simply do 2 passes: first create that large array and fill it. Then count the non zero entries! Create a new array with the smaller length, and then copy over all non zero elements manually.
I have used the method stated by #GhostCat but it made me change the code entirely. This is my new code
public static Object[] Divisi(int[] array, int target){
ArrayList<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer.add(array[i]);
}
}
return answer.toArray();
}
This gave me the desired answer but how else can i do this without converting to object
The shortest and the most quickest way to go about this is, you can change the array to an ArrayList and then use .toArray() method to get it back as a primitive array when returning.
public static Integer[] Divisible(int[] array, int target){
List<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0) {
answer.add(array[i]); // pushing to list only if the number is divisible
}
}
return answer.toArray(new Integer[0]); // converting the list to an array before returning
}
If you want a list of unique numbers use Set instead of a List.
Set<Integer> answer = new HashSet<>();
Instead of using the primitive int, I have conformed to using Integer instead.
Here is my solution.
public static Integer[] divisible(Integer[] array, int target) {
int j = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] % target == 0) {
j++;
list.add(array[i]);
}
}
Integer answer[] = new Integer[j];
answer = list.toArray(answer);
return answer;
}
You should use a separate counter for the result array and keep incrementing the counter if the number is divisible by the target.
Something like this :
int[] result=new int[array.length];
int resultindex=0; //create a separate counter
for(int i=0;i<array.length;i++)
{
if(array[i]%target==0)
{
result[resultindex]=array[i];
++resultindex; //update the counter
}
}
I want to create a program that reads int values from the user until a value that is not an int is introduced. Then i want to get how many numbers are equal.
I tried this code
import java.util.Scanner;
public class Equals {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Scanner input = keyboard;
int index = 0;
int equals = 0;
while(keyboard.hasNextInt()){
keyboard.nextInt();
index++;
}
int[] equals = new int[index];
for(int i = 0 ; i < index ; i++){
int aux = input.nextInt();
values[i] = aux;
for(int b = 0 ; b < index ; b++){
if(aux == values[b]){
equals++;
}
}
}
System.out.print(equals);
}
}
This code doesnt work because the keyboard scanner only gets the number of values introduced by the user and i use that for the array size but i cant get each individual value to compare. I cant use array lists.
If you can't use array lists, what can you use? Can you use this?
int[] values = new int[0];
while(keyboard.hasNextInt()){
values = Arrays.copyOf(values, values.length + 1);
values[values.length-1] = keyboard.nextInt();
index++;
}
And if you aren't allowed to do the arrays class, you can resize the array manually like this, and use this function instead of Arrays.copyOf:
private int[] resize(int[]s, int capacity) {
int[] copy = new int[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
return copy;
}
I have an array called arr, with place for 15 elements.
I need to place the numbers 1 through 15 in a random order into that array.
Here is what I have tried:
int[] arr = new int[15];
int i,j,k,n;
for (i = 0; i<15; i++) {
for (j=0; j<15; j++) {
n = (int)(Math.random() * 14 + 1);
if (rij[j] != n) {
rij[i] = n;
break;
}
}
}
Thanks! :)
Use an ArrayList and fill it up with numbers 1 to 15.
Shuffle the list.
Convert it to an array.
This seems like homework (or an interview question?). If that's the case and you are required to use arrays rather than the built in methods with the Java Collection Objects, (or even if not, really), the answer is the Fisher-Yates Shuffle algorithm
The modern in-place shuffle is:
To shuffle an array a of n elements (indexes 0..n-1):
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
(I'd have to check, but I suspect this is what Java uses under the hood for its shuffle() methods).
Edit because it's fun to implement algorithms:
In java, this would be:
public static void main(String[] args) {
int[] a = new int[15];
for (int i = 1; i <= 15; i++)
{
a[i-1] = i;
}
Random rg = new Random();
int tmp;
for (int i = 14; i > 0; i--)
{
int r = rg.nextInt(i+1);
tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
for (int i = 0; i < 15; i++)
System.out.print(a[i] + " ");
System.out.println();
}
And ... this can be further optimized using the inside-out version of the algo since you're wanting to insert a known series of numbers in random order. The following is the best way to achieve what you stated as wanting to do as there are no extra copies being made such as when creating an ArrayList and having it copy back out to an array.
a = new int[15];
Random rg = new Random();
for (int i = 0; i < 15; i++)
{
int r = rg.nextInt(i+1);
a[i] = a[r];
a[r] = i+1;
}
Do it like this
// Create an ordered list
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 16; i++) {
list.add(i);
}
// Shuffle it
Collections.shuffle(list);
// Get an Integer[] array
Integer[] array1 = list.toArray(new Integer[list.size()]);
// Get an int[] array
int[] array2 = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array2[i] = list.get(i);
}
This will leave the elements randomly shuffled in a Integer[], if that's fine with you:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 15; i++)
list.add(i + 1);
Collections.shuffle(list);
Integer[] arr = list.toArray(new Integer[0]);
I will do something like this:
First create a temporary arraylist filled with numbers from start to end, then using random select a number, copy it into array and remove it from the temp arraylist, repeat until the arraylist is empty...
ArrayList<Integer> arr = new ArrayList<Integer>();
int[] arr2 = new int[15];
int i,j,k,n;
for (i=0;i<15;i++) arr.add(i+1);
i=0;
while(arr.size()>0){
n = (int)(Math.random() * (14 + 1 - i));
arr2[i]=arr.get(n);
arr.remove(n);
i++;
}