Code:
package syfah;
import java.util.Scanner;
public class Adding{
public static int convert(char c){
if(c == 'A') return 10;
else if(c == 'B') return 11;
else if(c == 'C') return 12;
else if(c == 'D') return 13;
else if(c == 'E') return 14;
else if(c == 'F') return 15;
return c;
}
public static void main(String [] args){
Scanner kbd = new Scanner(System.in);
System.out.print("Enter How many Numbers to be added: ");
int inputting = Integer.parseInt(kbd.next());
String [] num = new String[inputting];
int []x = new int[inputting];
int a = 0;
int ans= 0;
int z = 0;
for(int i = 0; i<inputting; i++){
System.out.print("Enter Number "+(i+1) + ": ");
num[i]= kbd.next();
int l = num[i].length();
int v = 0;
for(int j = l-1; j>=0; j--){
if(Character.isLetter(num[i].charAt(v))){
a = convert(num[i].charAt(v));
}
else
a = Integer.parseInt(Character.toString(num[i].charAt(v)));
z = z + (a*(int)Math.pow(x[i], j));
v++;
}
ans = ans + z;
z = 0;
}
System.out.print("Enter Base of Sum: ");
int Lastbase = Integer.parseInt(kbd.next());
int x2 = ans;
int t = 0;
String LastAns = "";
if( Lastbase >= 10){
while(x2 != 0){
t = x2% Lastbase;
x2 = x2/ Lastbase;
if(t >= 10){
if(t == 10)
LastAns = "A" + LastAns;
else if(t == 11)
LastAns = "B" + LastAns;
else if(t == 12)
LastAns= "C" + LastAns;
else if(t == 13)
LastAns = "D" + LastAns;
else if(t == 14)
LastAns = "E" + LastAns;
else if(t == 15)
LastAns = "F" + LastAns;
}
else
LastAns = Integer.toString(t) +LastAns;
}
}
else{
while(x2 != 0){
t = x2% Lastbase;
x2 = x2/ Lastbase;
LastAns = Integer.toString(t) + LastAns;
}
}
String output = "Summation of the Following Numbers:";
for(int i = 0; i < inputting; i++){
output = output +"\n"+num[i]+" base "+x[i];
}
output = output+"\nSum = "+LastAns;
System.out.println(output+" with base "+ Lastbase);
}
}
Problems:
1. well i know how to put restriction that the user should only input not less than 2 and not more than 16 as base but my problem is how can i implement it inside my code.
2. how can i edit my code that it will ask the base of the first number to be inputted
and checks if its valid
ex.
i input originalbase of: 2
so if i inputted 1st number to be added like this: 10129223
it will make the user to input a new 1st number to be added to the 2nd and so on.
or simply it check if it matches the base inputted.
the desired out put is kinda like this:
Code:
Enter How many Numbers to be added: 3
Enter Number 1: f5
Enter Original Base: 1: 16
<--- and so on ---->
