Hello people, I was recently working on some homework for my class, and I have a error on my code. First, I will tell what I need to do.
What the program asks for is for a person to give a 3-number digit(N), from 100 to 999. After that, the program will do a addition that will give the number inserted, the addition will be of 2 numbers, the 1st one must be a 3 digit number while the second one must be a 2 digit number (the second one must use 2 of the digits of the third one, you slash one of the digits (no rearrange)).
Example :
N = 302
a + b = n
251 + 51 = 302
275 + 27 = 302
276 + 26 = 302
281 + 21 = 302
301 + 01 = 302
Right now this is my code :
import javax.swing.*;
import java.util.*;
public class Lab01A {
public static void main (String [] args) {
//Definicion de variables
int n = Integer.parseInt(JOptionPane.showInputDialog(null, "Por favor introduzca un numero de 3 digitos, de 100-999","Leer Arreglo",-1));
int a = 0;
int b = 0;
int con = 6;
String s = "" + n;
String s1 = "" + a;
String des = "Dar la N : " + n +"\n";
String p1 = s1.substring(0,1);
String p2 = s1.substring(1,2);
String p3 = s1.substring(2,3);
//Combinaciones
String p12 = p1+p2;
String p13 = p1+p3;
String p21 = p2+p1;
String p23 = p2+p3;
//Empieza aplicacion
if (n >= 100 && n<= 999){
for (a = 100; a<=n; a++){
for (int i = 0; i<4; i++) {
switch (i){
case 0 :
b = Integer.parseInt(p12);
case 1 :
b = Integer.parseInt(p13);
case 2 :
b = Integer.parseInt(p21);
case 3 :
b = Integer.parseInt(p23);
}
int z = a+b;
if(z == n){
des = des + a + " + " + b + " = " + n + "\n";
}
}
}
}
JOptionPane.showMessageDialog(null,des,"Resultados",-1);
}
}
and I receive the following errors :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1934)
at Lab01A.main(Lab01A.java:20)
Any help will be appreciated.