Can anyone answer this question?
public class AddingArray {
public static void main(String[] args){
int arry1[] = {2,3,4,5,6,7,9};
int arry2[] = {4,3,7,9,3,5};
for(int i = 0; i <arry1.length; i++){
int result = arry1[i] + arry2[i];
System.out.println("Result "+result);
}
}
}
Whenever I try executing the above code I get the error Exception in
thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at
basics.AddingArray.main(AddingArray.java:9)
But,my output should be like this 6,6,11,14,9,12,9
As people have mentioned, one of yours arrays is literally shorter than the other. Take two blocks and overlay them over only one block. The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.
I would make sure both of them are of the same size. If you do want to leave em as they are, I would do this:
int result = 0;
try
{
for(int i = 0, length = array2.length; i < length; i++)
{
result = array1[i] + array2[i];
System.out.println("Result is: " + result);
}
catch(Exception e)
{
System.out.println("You tried to do something that resulted in an error");
System.out.println("Your previous result was: " + result);
}
}
SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.
Let's make this as simple and understandable as possible, with no fancy annotations:
You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums. However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
You need to determine the length of the longest array. You can do this with a Math.max()-method, where you give the length of each array as parameters:
int biggestArrayLength = Math.max(arry1.length, arry2.length);
Then, instead of for(int i=0;i<arry1.length;i++){, you write:
for(int i=0;i<biggestArrayLength;i++){
Now it doesn't matter which of the two arrays is the biggest one.
Inside the loop, I would define two ints, representing a value from each of the two arrays:
int value1 = arry1[i];
int value2 = arry2[i];
however, this will give an error when the smallest array does not have any more elements. We need to check if the array actually has an element with index i. index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6. In other words, only index numbers that are lower (and not equal) to length, is valid numbers:
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
System.out.println("Result "+result);
}
}
}
Now, if you need to put these in a third array, say named sumArray, this would be the complete code:
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int biggestArrayLength = Math.max(arry1.length, arry2.length);
int[] sumArray = new int[biggestArrayLength];
for(int i=0;i<biggestArrayLength;i++){
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
sumArray[i] = result;
System.out.println("Result "+result);
}
}
}
It is because your loop will go from 0 to 6 (which is the array1.length - 1) and your array2 only has 6 elements (so from 0 to 5).
So when you are accessing arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException.
You could change your for loop to go to the length of the smallest array:
for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }
Or add an element in array2, but that is yours to decide since I do not know your requirements.
Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.
either do:
if(arry2[i] != null) {
//run your adding code
}
or change your arrays to be the same size
Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop. This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException.
Can we stop the downvoting?
End edit----
If you want to add up all of the elements in the array use this code.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result+=arry1[i];
}
for(int j=0; j < array2.length; j++){
result += array2[j];
}
System.out.println("Result: "+ result);
}
}
if you are trying to sum individual elements as you loop you can do the following. This will properly handle 2 arrays of different length regardless of which one is longer.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result=arry1[i];
if(i < array2.length){
result += array2[i];
}
System.out.println("Result: "+ result);
}
for(int j = i; j < array2.length; j++){
System.out.println("Result: "+ array2[j]);
}
}
}
Related
I'm trying to learn a bit Java with tutorials and currently I'm struggling with piece of code where I should find on which index is difference between arrays (if there is difference at all)
My code
Scanner scanner = new Scanner(System.in);
int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int sumArrOne = 0;
int index = 0;
boolean diff = false;
for (int k : arrOne) {
if (Arrays.equals(arrOne, arrTwo)) {
sumArrOne += k;
} else {
for (int i : arrTwo) {
if (k != i) {
index = i;
diff = true;
break;
}
}
}
}
if (diff) {
System.out.println("Found difference at " + index + " index.");
} else {
System.out.println("Sum: " + sumArrOne);
}
So, if arrays are identical I'm sum array elements in arrOne. If they are not identical -> must show at which index they are not.
With this code when I input
1 2 3 4 5
1 2 4 3 5
I should get that difference is at index 2 instead I've got index 1.
I'm not quite sure why and would be glad if someone point me out where is my mistake.
I updated your code. Looks like you're misunderstanding the concept of indexes yet.
Use one common index to check with in both arrays, in my example it's simply called i:
import java.util.Arrays;
import java.util.Scanner;
public class BadArray {
static private final int INVALID_INDEX = Integer.MIN_VALUE;
public static void main(final String[] args) {
try (final Scanner scanner = new Scanner(System.in);) {
final int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
final int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int sumArrOne = 0;
int diffIndex = INVALID_INDEX;
final int minLen = Math.min(arrOne.length, arrTwo.length);
for (int i = 0; i < minLen; i++) {
sumArrOne += arrOne[i];
if (arrOne[i] != arrTwo[i]) {
diffIndex = i;
break;
}
}
if (diffIndex != INVALID_INDEX) {
System.out.println("Found difference at " + diffIndex + " index.");
} else if (arrOne.length != arrTwo.length) {
System.out.println("Arrays are equal but have different length!");
} else {
System.out.println("Sum: " + sumArrOne);
}
}
}
}
I also put the scanner into a try-resource-catch to handle resource releasing properly.
Note you could also do the array lengths comparison right at the start if different array lengths play a more crucial role.
You are trying to find out which index has the first difference so you should iterate via the index rather than using a for-each loop (aka enhanced for loop). The following method should work for this.
/**
* Returns the index of the first element of the two arrays that are not the same.
* Returns -1 if both arrays have the same values in the same order.
* #param left an int[]
* #param right an int[]
* #return index of difference or -1 if none
*/
public int findIndexOfDifference(int[] left, int[] right) {
// short-circuit if we're comparing an array against itself
if (left == right) return -1;
for (int index = 0 ; index < left.length && index < right.length ; ++index) {
if (left[index] != right[index]) {
return index;
}
}
return -1;
}
In your code you compare, where the indexes are different, not the values at the indexes. Also your code has several other issues. I'll try to go through them step by step:
// compare the whole array only once, not inside a loop:
diff = !Arrays.equals(arrOne, arrTwo));
if (!diff) {
// do the summing without a loop
sumArrOne = Arrays.stream(arrOne).sum();
} else {
// find the difference
// it could be the length
index = Math.min(arrOne.length, arrTwo.length);
// or in some different values
for (int i = 0; i < index; i++) { // do a loop with counter
if (arrOne[i] != arrTwo[i]) {
index = i;
break;
}
}
}
It doesn't matter that I set index here above the loop as it's value will be overwritten anyways inside the loop, if relevant.
I have to create a program which adds two integers and prints the sum vertically.
For example, I have.
a=323, b=322.
The output should be:
6
4
5
I've created the code for when the integers are up to two digits, but I want it to work for at least three digits.
Below is the best I could think of.
It may be completely wrong, but the only problem I'm facing is the declaration of array.
It says that the array might not be initialized.
If I set it to null then also it won't assign values to it later.
I know maybe I'm making a big mistake here, but I'll really appreciate if anyone could help me out.
Please keep in mind that I must not use any other functions for this code.
Hope I'm clear.
public class Vert
{
public static void main(String args[])
{
int n,i=0,j,a=323,b=322;
int s[];
n=a+b;
while(n>9)
{
s[i]=n%10;
i++;
s[i]=n/10;
if(s[i]>9)
{
n=s[i];
}
}
j=i;
for(j=i;j>=0;j--)
{
System.out.println(+s[j]);
}
}
}
String conversion seems like cheating, so here's a Stack.
int a = 323, b = 322;
java.util.Stack<Integer> stack = new java.util.Stack<>();
int n = a + b;
while (n > 0) {
stack.push(n % 10);
n = n / 10;
}
while (!stack.isEmpty())
System.out.println(stack.pop());
If an array is required, you need two passes over the sum
int a = 323, b = 322;
// Get the size of the array
int n = a + b;
int size = 0;
while (n > 0) {
size++;
n = n / 10;
}
// Build the output
int s[] = new int[size];
n = a + b;
for (int i = size - 1; n > 0; i--) {
s[i] = n % 10;
n = n / 10;
}
// Print
for (int x : s) {
System.out.println(x);
}
To initialize an array, you need to specify the size of your array as next:
int s[] = new int[mySize];
If you don't know the size of your array, you should consider using a List of Integer instead as next:
List<Integer> s = new ArrayList<Integer>();
Here is how it could be done:
// Convert the sum into a String
String result = String.valueOf(a + b);
for (int i=0; i <result.length();i++) {
// Print one character corresponding to a digit here per line
System.out.println(result.charAt(i));
}
I'd do it like this:
int a = 322;
int b = 322;
int sum = a + b;
String s = Integer.toString(sum);
for(int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
But your problem looks like an array is required.
The steps are same as in my solution:
Use int values
Sum the int values (operation)
Convert the int value in an array/string
Output the array/string
I'm trying to find out particular elements in my ArrayList (arrayOne). Each element should be an int[]. I've tried System.out.println(arrayOne), which compiles but gives a irregular and strange number "[[I#370968]".
I've also tried System.out.println(arrayOne[0]) but it won't compile and emits the error
Array required but java.util.ArrayList found.
Given is the following code, with {1,12,3,13,123,2} passed to eg:
import java.util.ArrayList;
public class arrayTest {
private ArrayList<int[]> arrayOne;
public arrayTest(int[] eg) {
int[] xy = new int[2];
arrayOne = new ArrayList<int[]>(eg.length);
for (int i = 0; i < eg.length; i++) {
int sv = String.valueOf(eg[i]).length();
if (sv == 1) {
xy[0] = 0;
xy[1] = eg[i];
arrayOne.add(xy);
}
else if (sv == 2) {
System.out.println("two digits");
// TODO add code to make xy[0] = the first
// digit of eg and xy[1] = the second digit
}
else {
System.out.println("too many digits");
// and throw error accordingly
}
System.out.println(arrayOne);
}
}
}
How do make sure and print out the int array at arrayOne[0]
Given the code above if (sv == 2) and i want to split each individual number into an int[] with [0] being the first digit and [1] being the second digit how would i get the int value of each individual digit.
Use Arrays.toString(yourArray); to print out arrays in human readable form.
First of all, the string [I#370968 is displayed because you are trying to print an int[], which is actually an object. Because this object does not override the object's toString() method, that method is derived from the Object class. The Object.toString() implementation, which prints the class name (in this case [I, because it is an int array), then an # sign, and then the hash code of the object.
Your ArrayList contains a number of int[]s. Because an ArrayList is not an array (the one with the square brackets, like int[]), you can't call an element on it as if it were an array. In short, you cannot call arrayOne[someDesiredIndex].
In order to get an element from the ArrayList, call get(int index) on it; it returns the desired int[]. As already pointed out by another answer, you can use Arrays.toString(int[]) to print it in a human readable form.
To answer your questions:
You can retrieve the first index (0) of the first array inside arrayOne with the following code: arrayOne.get(0)[0].
The following code should work:
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
Above method puts each digit into the next array position (it also works with digits greater than 99). With this method you can easily get each individual digit:
int[] digits = intToArray(47);
int a = digits[0]; // Will be 4
int b = digits[1]; // Will be 7
So this is the class rewritten:
public class Rewrite {
private ArrayList<int[]> arrayOne = new ArrayList<int[]>();
public Rewrite(int[] eg) {
for (int i = 0; i < eg.length; i++) {
int length = String.valueOf(eg[i]).length();
switch (length) {
case 1:
this.arrayOne.add(new int[] { 0, eg[i] });
break;
case 2:
this.arrayOne.add(intToArray(eg[i]));
break;
default:
throw new IllegalArgumentException("Number " + eg[i] + " has too many digits");
// Or display the error or something.
}
System.out.println(Arrays.toString(this.arrayOne.get(i)));
}
}
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
public static void main(String[] args) {
Rewrite r = new Rewrite(new int[] { 47, 53, 91, 8 });
}
As the title reads, I have been thinking about creating multiple nested loops that aim to achieve one purpose. Move two generated random numbers between 0-9 through each possible possition of an array.
For example, App generates first number (fNum) 1 and second number (sNum) 6. It then moves these numbers in the array which containts ABC. However firstNum and secondNum will need to also try all the possible combinations, so each one will need to be different with each loop.
-1ABC6
-A1BC6
-AB1C6
-ABC16
-ABC61
-AB6C1
-A6BC1
-6ABC1
-A6B1C
-A61BC
-A16BC
-A1B6C
-A1BC6
and so on...
I beleive the best way will be to create a method for generating a counter, which increments the numbers which I can call.
private int getNextNumber(int num) {
if (num == 0) {
return num;
} else {
num++;
}
if (num < 10) {
return num;
} else {
return -1;
}
}
Then I will need multiple nested loops... I have decided to go for several loops which will go infinitly.
while (j < maxlen) {
//J = 0 and maxlen = length of text so in this case 3 as it is ABC
//Add two numbers and check against answer
while (fNum != -1 || sNum != -1) {
//incrememnt numbers
fNum = getNextNumber(fNum);
System.out.println(fNum);
sNum = getNextNumber(sNum);
System.out.println(fNum);
}
String textIni = "ABC";
int lenOfText = textIni.length();
char[] split = textIni.toCharArray();
for (int i = 0; i < lenOfText; i++) {
//here it will look at the length of the Text and
//try the possible positions it could be at....
//maybe wiser to do a longer loop but I am not too sure
}
}
Since you don't need to store all possible combinations, we will save some memory using only O(n) storage with an iterative solution. I propose you a basic implementation but don't expect to use it on large arrays since it has a O(n³) complexity.
public static void generateCombinationsIterative(List<Integer> original, int fnum, int snum) {
int size = original.size();
for (int i=0 ; i<=size ; i++) {
List<Integer> tmp = new ArrayList<>(original);
tmp.add(i,fnum);
for (int j=0 ; j<=size + 1 ; j++) {
tmp.add(j,snum);
System.out.print(tmp + (i == size && j == size + 1 ? "" : ", "));
tmp.remove(j);
}
}
}
For your culture, here is an example of a recursive solution, which takes a lot of memory so don't use it if you don't need to generate the lists of results. Nevertheless, this is a more general solution that can deal with any number of elements to insert.
public static List<List<Integer>> generateCombinations(List<Integer> original, Deque<Integer> toAdd) {
if (toAdd.isEmpty()) {
List<List<Integer>> res = new ArrayList<>();
res.add(original);
return res;
}
int element = toAdd.pop();
List<List<Integer>> res = new LinkedList<>();
for (int i=0 ; i<=original.size() ; i++)
// you must make a copy of toAdd, otherwise each recursive call will perform
// a pop() on it and the result will be wrong
res.addAll(generateCombinations(insertAt(original,element,i),new LinkedList<>(toAdd)));
return res;
}
// a helper function for a clear code
public static List<Integer> insertAt(List<Integer> input, int element, int index) {
List<Integer> result = new ArrayList<>(input);
result.add(index,element);
return result;
}
Note that I did not use any array in order to benefit from dynamic data structures, however you can call the methods like this :
int[] arr = { 1,2,3 };
int fnum = 4, snum = 5;
generateCombinationsIterative(Arrays.asList(arr),fnum,snum);
generateCombinations(Arrays.asList(arr),new LinkedList<>(Arrays.asList(fnum,snum));
Note that both methods generate the combinations in the same order.
I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}