Why is this program giving "division by zero" error? - java

Give one point to A[i] if either A[i]%A[j] ==0 or A[j]%A[i] == 0
Calculating the total points received by every element.
Input: A={2,3,4,5,6}
Output: 2,1,1,0,2
I am getting this error message: Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:29)
class Main {
public static void main(String args[])
{
ArrayList<Integer> al
= new ArrayList<>();
al.add(2);
al.add(3);
al.add(4);
al.add(5);
al.add(6);
int c=al.size()-1;
while(c>=0){
int count=0;
for (int i=0; i<al.size(); i++){
if(i==c){
break;
}
else{
if(al.get(c)>al.get(i)){
if(al.get(c)%al.get(i) == 0){
count++;
}
}
else{
if(al.get(i)%al.get(c) == 0){
count++;
}
}
}
}
al.set(1,count);
--c;
}
for(int i : al){
System.out.print(i);
}
}
}

When you are running the code, this line:
al.set(1,count);
Can set count = 0. So when the value at slot 1 will be used, it will throw the error.
For "where is the error", java has pretty error informations, and it will return something like:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.me.myprogram.MainClass.main(MainClass.java:61)
And you will see that the line 61 is:
if(al.get(c) % al.get(i) == 0){
I suggest you to check when it's 0, or to don't set 0 count like check if it's 0, and set 1, for example:
if(count != 0) {
al.set(1, count); // here the value will change only if we could use it after
} /* With this part, it will change the value but also preventing all issue with /0
else {
al.set(1, 1);
}
*/

Related

Android : CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1

I have an error it says
Caused by: android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
I don't know what causes the error, the error is on the line cursor.getString(17)); need help
Cursor cursor_other_card = MainActivity.sqLiteHelper.getData("SELECT ocv.id,ocv.card_holder_name,ocv.card_number_system_generated,ocv.card_number_inputted,ocv.card_number_series,ocv.distribution_status,ocv.release_date,ocv.release_by,ocv.release_place,ocv.card_physically_presented,ocv.card_pin_is_attached,ocv.reason_not_presented,ocv.reason_unclaimed,ocv.card_replacement_requests,ocv.card_replacement_request_submitted_details,ocv.pawning_remarks,ocv.other_image, ocv.others_reason_not_presented,ocv.others_reason_unclaimed FROM other_card_validations AS ocv LEFT JOIN emv_validation_details AS evd ON evd.id = ocv.emv_validation_detail_id WHERE evd.id="+id);
Integer i =0;
while (cursor_other_card.moveToNext()) {
i++;
//5 other_card_validations
myEdit.putString("card_holder_name"+i+"_u",cursor_other_card.getString(1));
myEdit.putString("card_number_system_generated"+i+"_u",cursor_other_card.getString(2));
myEdit.putString("card_number_inputted"+i+"_u",cursor_other_card.getString(3));
myEdit.putString("card_number_series"+i+"_u",cursor_other_card.getString(4));
myEdit.putString("distribution_status"+i+"_u",cursor_other_card.getString(5));
myEdit.putString("release_date"+i+"_u",cursor_other_card.getString(6));
myEdit.putString("release_by"+i+"_u",cursor_other_card.getString(7));
myEdit.putString("release_place"+i+"_u",cursor_other_card.getString(8));
myEdit.putString("card_physically_presented"+i+"_u",cursor_other_card.getString(9));
myEdit.putString("card_pin_is_attached"+i+"_u",cursor_other_card.getString(10));
myEdit.putString("reason_not_presented"+i+"_u",cursor_other_card.getString(11));
myEdit.putString("reason_unclaimed"+i+"_u",cursor_other_card.getString(12));
myEdit.putString("card_replacement_request"+i+"_u",cursor_other_card.getString(13));
myEdit.putString("card_replacement_request_submitted_details"+i+"_u",cursor_other_card.getString(14));
myEdit.putString("pawning_remarks"+i+"_u",cursor_other_card.getString(15));
if (cursor_other_card.getBlob(16) != null) {
if (i == 1) {
ocv_other_image_1_u = cursor_other_card.getBlob(16);
} else if (i == 2) {
ocv_other_image_2_u = cursor_other_card.getBlob(16);
} else if (i == 3) {
ocv_other_image_3_u = cursor_other_card.getBlob(16);
} else if (i == 4) {
ocv_other_image_4_u = cursor_other_card.getBlob(16);
} else if (i == 5) {
ocv_other_image_5_u = cursor_other_card.getBlob(16);
}
}
myEdit.putString("others_reason_not_presented"+i+"_u", cursor.getString(17)); //the error goes here
myEdit.putString("others_reason_unclaimed"+i+"_u", cursor.getString(18));
}
cursor_other_card.close();
You have an off by 1 error.
Integer i =0;
while (cursor_other_card.moveToNext()) {
i++;
//5 other_card_validations
myEdit.putString("card_holder_name"+i+"_u",cursor_other_card.getString(1));
For an array of N, this code would make I go 1 to N, instead of 0 to N-1. To fix this, increment i at the end of the loop, not the beginning.
Also, you should make it int i=0, not Integer. No reason to use the class when a primitive is available.

why do I get an "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0 "

I have to backtracking with numbers in a list that represent restrictions, such as: "x1 + x2> = 1". And if it meets all the conditions, that array is added to another array, in addition there is another list that represents the sum that I must make with all the variables "x1 + x2 + x3 + x4" and with that search for the one with the minimum value.
good what I should do in backtraking is to make a binary matrix with all the possibilities that the restrictions meet. What I have done is this but I get the error: "Exception in thread" main "java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0" and I don't know where my problem is.
import java.util.ArrayList;
public class Pra_hacer_pruebas {
public static void main(String[] args) {
Pra_hacer_pruebas a = new Pra_hacer_pruebas();
ArrayList<Integer> conf1= new ArrayList<>(); // conf1 is the list that will contain one of the possibilities that may or may not be added to the binary matrix.
ArrayList<ArrayList<Integer>>pos_v = new ArrayList<>();// pos_v is where the possibilities will be added, binary matrix
int[][] restric = new int[2][2];// restric is the list with restrictions
restric[0][0]=2;
restric[0][1]=1;
restric[1][0]=4;
restric[1][1]=2;
for(int t=0;t<4;t++){
conf1.set(t, -1);
}
//System.out.println(conf.get(i));
a.binario(conf1,restric,0,0,0,pos_v,0,4,-1);
}
public void binario(ArrayList<Integer> conf1, int[][] restric, int suma,int filas,int columnas,ArrayList<ArrayList<Integer>> pos_validas,int posicion, int cont,int bin){
//filas = rows, suma= sum is to see if it meets the condition, columnas = columns, pos_validas = pos_v, posicion is to advance the rows of the matrix, cont: is the amount of different variables, bin is the binary variable
Boolean booleano = false; // booleano is the flag that if it is true it is because there was a null position (-1)
for (int[] restric1 : restric) {
suma=0;
for (int co = 0; co < restric1.length; co++) {
if ((conf1.get(restric1[co]) == 1) || (conf1.get(restric1[co]) == 0)) {
suma = suma + conf1.get(restric1[co]);
} else {
booleano = true;
}
}
if (booleano == false) {
if (suma < 1){
break;
}
}
}
if (booleano == false) {
pos_validas.set(posicion, conf1);
posicion++;
}
for (int f = 0; f < cont; f++) {
if (conf1.get(f) < 1) {
bin++;
conf1.set(f, bin);
binario(conf1,restric,suma,filas,columnas,pos_validas,posicion,cont,bin);
}
bin--;
}
}
}
Try add method. Even if you create ArrayList with initialCapacity, It won't works as you intended. If you print ArrayList size before set, You can check it.
System.out.println(conf1.size());
for(int t=0; t<4; t++){
conf1.set(t, Integer.valueOf(-1));
}
Modify code to use add
for(int t=0; t<4; t++){
conf1.add(-1);
}
your Arraylist objects start out as empty objects. YOu can't call .set() on them at all: Those UPDATE existing entries, they don't make new ones. Try add.

Why does my method return the wrong value?

Even though my method operationsNeeded prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if operationsNeeded is executed 4 times, count1 is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:
check: 4
check: 4
check: 3
check: 2
I would expect my program to execute this only once and then continue to the return statement.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
Your method is recursive. The "check: " line is printed on each level of that recursion, with the value that it currently has on that level. It first prints the "inner-most" value (4), than that of the level above (also 4), and finally hte value in the top-level, which is 2 after being incremented in the if above. And the value it returns is always the value from to top-level.
If you want to print it only once, you could print it on the inner-most level only, using else. However, that will still return the value from the top-level iteration; instead, keep track of the value returned from the recirsive call and update count1 accordingly.
if (! isAllTheSame(relevantList)) {
// we have to go deeper!
count1 = operationsNeeded(updatedList, count1 + 1);
} else {
// phew, finally done
System.out.println("check: " + count1);
}

String index out of bounds

This is my code to add to binary strings, I am getting correct value in res string but it still gives me an exception at the end of execution.
The strings m1 & m2 are of equal length of 28 each.
Still I tried running the loop just 10 times to verify but error still persists.
This holds true for any value of i, irrespective of greater than or lesser than actual length of both strings.
public static String addMantissa(String m1,String m2)
{
String res=" ";
int c=0;
System.out.println("Length is " + m2.length());
int i=0;
while(i < m2.length())
{
System.out.print(" " + res.charAt(i));
if(m1.charAt(i)=='1' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="0";
c=1;
}
else
{
res+="1";
c=1;
}
}
if(m1.charAt(i)=='1' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="0";
c=0;
}
else
{
res+="1";
c=0;
}
}
i++;
}
return res;
}
Thanks in advance.
Your entire method can be replaced by just one line:
public static String addMantissa(String m1, String m2) {
return new BigInteger(m1, 2).add(new BigInteger(m2, 2)).toString(2);
}
The size of 28 bits mentioned in your question means that the Integer class could have neen used for parsing, but using BigInteger means that strings of any size can be handled.
You should use the JDK instead of reinventing the wheel.
Also, "less code is good" is a great mantra (provided the code remains clear, of course), and this code has high density.
#ShreyosAdikari is basically right.
System.out.print(" " + res.charAt(i));
Should be called at the end of the loop, as then res[i] is filled.
Maybe you meant:
System.out.print((" " + res).charAt(i));
But then you do not print the last loop's res.
Actually the exception comes from the line
while(i < m2.length())
You need to change it to
while(i < m2.length() && i<m1.length())
As if m1(say 1) has a length lower than m2(say 4) and you checking only the value of m2. Then in the second iteration it will enter the loop as 2<4, and when it tryes to get m1.carAt(2) (as the length 1) it will throw String index out of bounds exception.

Use value outside for loop

public class randomdemo {
public static void main(String[] args)
{
Random rand = new Random();
int [] varArray = new int[rand.nextInt(10)];
System.out.println(varArray.length);
int d = rand.nextInt(1999)-1000;
for (int i=0;i<varArray.length;i++)
{
varArray[i]= rand.nextInt(1999)-1000;
System.out.println(varArray[i]);
if(d==varArray[i])
{
System.out.println(d);
System.out.println(i+1);
}
else
{
System.out.println(d);
System.out.println(0);
}
}
}
}
Problems in code:
It executes the if-else statement multiple times and displays the if-else output multiple times since it is in for loop.
The code should execute the if-else statement only once but the rest of the for loop should be executed multiple times.
Since the if statement is using value of varArray[i] I cannot exclude the code from the for loop.
When break statement is used it is terminating the for loop. and the complete output is not shown.
output: currently
7
-710
-249
0
-693
-249
0
172
-249
0
-488
-249
0
-48
-249
0
955
-249
0
869
-249
0
As you can see the length of array is 7
it displays array element then value of variable d and value 0 in a loop.
expected output:
7
-710
-693
172
-488
-48
955
869
-249
0
the output of array with 7 elements should be 7 array values followed by variable d and 0.
May be you can set a boolean flag to track execution of your if else code .. see code below.
boolean flag = false; // flag to track the if else
System.out.println(varArray.length);
int d = rand.nextInt(1999)-1000;
for (int i=0;i<varArray.length;i++)
{
...
if(!flag){
if(d==varArray[i])
{
flag =true;
System.out.println(d);
System.out.println(i+1);
}
else
{
flag =true;
System.out.println(d);
System.out.println(0);
}
}
Please identify the exact scenario in which you want to execute the if-else and make changes in the existing if-else condition so that it executes only once in the loop. Or you can wrap the existing if-else inside other if-else,for which the condition can be the scenario in which you have to execute the inner if-else.
For eg: Let the scenario is like only for a particular value of i(say when i=10) you want to execute the loop.Please modify the code as below.
if(i==10){
if(d==varArray[i])
{
System.out.println(d);
System.out.println(i+1);
}
else
{
System.out.println(d);
System.out.println(0);
}
}
Try this.
public class randomdemo {
public static void main(String[] args) {
Random rand = new Random();
int[] varArray = new int[rand.nextInt(10)];
System.out.println(varArray.length);
int d = rand.nextInt(1999) - 1000;
int foundIdx = -1; // mark index if you find one!
for (int i = 0; i < varArray.length; i++) {
varArray[i] = rand.nextInt(1999) - 1000;
System.out.println(varArray[i]);
if (d == varArray[i]) {
foundIdx = i + 1; // only the last match is saved
}
}
if (foundIdx != -1) {
System.out.println(d);
System.out.println(foundIdx);
} else {
System.out.println(d);
System.out.println(0);
}
}
}

Categories