The index 0 is out of range - java

I'm getting a 'The index 0 is out of range' exception in the following try-catch block but I can't for the life of me figure out where the exception gets thrown?
try{
cs = this.con.prepareCall("{call "+storedProcName+"("+procParams+")}");
for(int j = 0; j < params.length; j++){
if (paramTypes[j].equalsIgnoreCase("Int")) {
int x = 0;
try{
x = Integer.parseInt(params[j]);
} catch(Exception e) {}
cs.setInt(j, x);
} else if (paramTypes[j].equalsIgnoreCase("Boolean")) {
boolean x = false;
try{
x = (params[j].equalsIgnoreCase("True")) || (params[j].equalsIgnoreCase("T")) || (params[j].equalsIgnoreCase("1")) || (params[j].equalsIgnoreCase("Yes")) || (params[j].equalsIgnoreCase("Y"));
} catch(Exception e) {}
cs.setBoolean(j, x);
} else if (paramTypes[j].equalsIgnoreCase("String")) {
cs.setString(j, params[j]);
}
}
}catch(Exception e){
System.out.println("---------------------------------------------");
System.out.println("Problem constructing callableStatement: "+e);
System.out.println("---------------------------------------------");
}
Thanks to anyone having a look at this and maybe point me in the right direction!

The indices for parameters in a PreparedStatement start at 1, not at 0.
So the first parameter has index 1. If you try to use 0 as an index, it will complain that that's not a valid index.

PreparedStatement parameter indexes start at 1 - so you probably just want
setString(j + 1, params[j]);
etc

The index of the first parameter is 1, not 0

try to use
System.out.println("Problem constructing callableStatement: "+e.getMessage);
to find out the stacktrace and the "trouble" line of code.

} else if (paramTypes[j]
Shouldn't that be params[ j ]?

Related

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

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);
}
*/

Cannot reach statement

I made a method which purpose is to delete list of questions. The method Test contains questions, answers, number of questions, points. And works fine.
I get the following error:
Unreachable statement on : System.out.println("The test \"" + tests[indice - 1].getNomTest());
Here is the code:
public static int supprimerTest(Test[] tests, int nbrTests) {
int longueurTests = tests.length;
int indice = 0;
int noTest = 1;
int saisieNoTest = 0;
String nomTest;
System.out.println("***DELETE A TEST***\n");
if (nbrTests > 0) {
boolean fin = true;
do{
System.out.print("Please enter a number of the question to be deleted");
try {
indice = Clavier.lireInt();
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
}
}catch (Exception e) {
if (nbrTests < 1){
System.out.print("ERROR ! the number must be between 1 and " + nbrTests + "try again...");
}else {
System.out.println("ERROR ! the number must 1. ... Try again...");
}
}
}while (fin);
}else {
System.out.println("Il n'existe aucun test.");
System.out.print ("\nTPress <ENTRER> to continue ...");
Clavier.lireFinLigne();
}
return nbrTests;
}
Thank you for your help.
The reason you have that error is because exceptions act similar to a return statement where it'll get caught by the nearest Exception handler.
Since you have:
throw new IndexOutOfBoundsException();
Any code underneath that throw will never be reached because it immediately jumps to your catch block.
I hope that makes sense. :)
When you use try statement, it throws exceptions automatically if it is being detected. Therefore, simply take out the throw exception line, then your code should work.
When you throw an exception, the code below the throw will be not executed. Throw invoke exception and the method can continue only in catch/finally block. Lines after throw new IndexOutOfBoundsException(); cannot be reached. Maybe your code should be following:
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;

How to continue excute next if statement when the former if statement have an error

Here are my codes.
try{
if("**".equals(state[i][j-1])){
state[i][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j-1] = true;
}
if("**".equals(state[i+1][j-1])){
state[i+1][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j-1] = true;
}
if("**".equals(state[i+1][j])){
state[i+1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j] = true;
}
if("**".equals(state[i][j+1])){
state[i][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j+1] = true;
}
if("**".equals(state[i-1][j+1])){
state[i-1][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j+1] = true;
}
if("**".equals(state[i-1][j])){
state[i-1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j] = true;
}
}catch(Exception a){
//continue next if statements;
}
What should I write in the catch scope?
Or whether I should rewrite the statement? And how?
The simple answer is, you don't; if you want an exception in one part of the code to not cause another part to be skipped over, you have to put them in different try blocks. In your case, however, there is an elegant solution, looping to represent many different try blocks with a single block of code:
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (l - j == k - i) continue;
try {
if("**".equals(state[k][l])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
} catch (Exception e) {
//do nothing, loop to next try block
}
}
}
I would kindly suggest to rewrite your code with less repetition. You keep checking for the same condition in different cells of state array. So I would suggest something like this:
for(k=i-1;k<i+1;k++){
for(l=j-1;l<j+1;l++){
try{
if("**".equals(state[k][k])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
}catch(Exception e){
//Even if you get an exception while the if statement is evaluated,
//the loop will continue to execute the next if snippet
continue;
}
}
}
Of course I cannot guarantee that this is the snippet you need, but I think you get the logic I propose.
Hope I helped!

efficient way to find gcd pairs for an upper bound number, 10000 in java

I want to find pairs having GCD=1 upto a certain number, say 10000.
I am using 2 nested loops and calling a method with long parameters.
but code is running damn slow, any efficient approach is required.
Thanks
class FastGCD {
public static long GCD(long a, long b) {
return (b == 0 ? a : GCD(b, a % b));
}
public static void main(String ah[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = 0;
long number = 0, output = 0;
try {
cases = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
System.exit(0);
} catch (IOException e) {
System.exit(0);
}
for (int i = 1; i <= cases; i++) {
try {
number = Long.parseLong(br.readLine());
} catch (NumberFormatException e) {
e.printStackTrace();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
for (int j = 0; j < number; j++) {
for (int k = 0; k < number; k++) {
if (FastGCD.GCD(j, k) == 1)
{
//System.out.println("here"+j+","+k);
output++;
}
}
}
System.out.println(output);
}
}
}
Many of these problems are already solved.
Check wikipedia or other sources for algorithms.
One of this is the Euclidean algorithm
though more exist
To generate the co prime numbers (Which you seem to want)
This Should help
Generating all coprime pairs
All pairs of coprime numbers m, n can be arranged in a pair of disjoint complete
ternary trees, starting from (2,1) (for even-odd or odd-even pairs)
or from (3,1) (for odd-odd pairs).
The children of each vertex
(m,n) are generated as follows:
Branch 1: (2m-n,m)
Branch 2: (2m+n,m)
Branch 3: (m+2n,n)
This scheme is exhaustive and non-redundant with no
invalid members.
from Wikipedia
These two ternary trees can easily be build in Java (one starting with (2,1), the other one starting with (3,1)).
You can put your upper bound inside the generation function.
It will be much more efficient than your brute-force approach.

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.

Categories