mardi 2 octobre 2018

sum vectors from the same array java [on hold]

I am a beginner in the programming world and I am trying to solve an exercise. But I get totally stuck.

The problem is: having 4 possible formats:

    ?<int><int><int><int>
<int>?<int><int><int>
<int><int>?<int><int>
<int><int><int>?<int>
<int><int><int><int>?

I have to solve the ? in each case, but taking into account the second vector is multiplied by 3, the third by 1 and the fourth by 0 and the last vector is subtracted.

    class LeaderBoard{
public static void main(String[] args){
String errorFormat = "Format error: You must write 4 integers and one symbol ?";

int[] list = null;
int position = -1, j = 0;

if(args.length!=5){
System.err.println(errorFormat);
}else{
try {
list = new int[4];
for(int i=0;i<args.length;i++){
if(position== -1 && args[i].equals("?")){
position = i;
}else if((position!= -1 && args[i].equals("?")) || (j==4)){
//Hay mas de un ? o no hay ?
System.err.println(errorFormat);
System.exit(1);
}else{
list[j] = Integer.parseInt(args[i]);
j++;
}
}
} catch (NumberFormatException e) {
System.err.println(errorFormat);
System.exit(1);
}

System.out.println("The missing value is "+calculate(position,list)); 
} 
}

static int calculate(int position, int[] list) {
    if (position == 0){
        positon=list[i]+list[i+1]*3+list[i+2]*1+list[i+3]*0-list[i+4];
    } else if (position == 1) {
        positon=list[i]+list[i+1]*3+list[i+2]*1+list[i+3]*0-list[i+4];
    } else if (position ==2 ) {
        positon=list[i]+list[i+1]*3+list[i+2]*1+list[i+3]*0-list[i+4];
    } else if (position ==3 ) {
        positon=list[i]+list[i+1]*3+list[i+2]*1+list[i+3]*0-list[i+4];
    } else if (position == 4) {
        positon=list[i]+list[i+1]*3+list[i+2]*1+list[i+3]*0-list[i+4];
    }
    return 0;
}

I'd like to use some loop like for, but I find it impossible, then I just use if/else if. Could someone help me?

Aucun commentaire:

Enregistrer un commentaire