Calculate with numbers from different number systems
This program calculates with numbers from different number systems and outputs the result in the desired number system.
You call it like that:
java Calculator <operator> <number> <base> <otherNumber> <base> (solutionBase)
Unfortunately it does not work with floating point numbers.
Example:
$java Calculator + 5234 7 FABCD43 16 3
200022201200110011
My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?
public class Calculator {
public static void main(String args) {
// display usage if user wants so
if (args[0].contains("help")) {
displayHelp();
return;
}
// parse arguments
String operator = args[0];
String number1 = args[1];
int baseOfNumber1 = Integer.parseInt(args[2]);
String number2 = args[3];
int baseOfNumber2 = Integer.parseInt(args[4]);
int baseOfSolution = 0;
if (args.length == 6) {
baseOfSolution = Integer.parseInt(args[5]);
}
int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);
int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);
// calculate and print out
int solutionDec = 0;
if (operator.equals("+")) {
solutionDec = number1Dec + number2Dec;
} else if (operator.equals("-")) {
solutionDec = number1Dec - number2Dec;
} else if (operator.equals("x")) {
solutionDec = number1Dec * number2Dec;
} else if (operator.equals("/")) {
solutionDec = number1Dec / number2Dec;
}
if (args.length == 6) {
System.out.println(decimalToRandomBase(solutionDec,
baseOfSolution));
} else {
System.out.println(solutionDec);
}
}
private static int randomBaseToDecimal(String number, int base) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
result = base * result + digit;
}
return result;
}
// works only till base 16
private static String decimalToRandomBase(int number, int base) {
StringBuilder finalNumber = new StringBuilder();
while (number != 0) {
if ((number % base) > 9) {
switch ((number % base)) {
case 10: finalNumber.append("A"); break;
case 11: finalNumber.append("B"); break;
case 12: finalNumber.append("C"); break;
case 13: finalNumber.append("D"); break;
case 14: finalNumber.append("E"); break;
case 15: finalNumber.append("F"); break;
}
} else {
finalNumber.append(number % base);
}
number = number / base;
}
return new StringBuilder(finalNumber).reverse().toString();
}
private static void displayHelp() {
System.out.println("This program calculates with numbers of different bases");
System.out.println("Example: ");
System.out.println("java Calculator + 34 5 554 6");
System.out.println("You can also specify the base of the output number as the last argument:");
System.out.println("java Calculator + 34 5 554 6 2");
}
}
java calculator number-systems
add a comment |
This program calculates with numbers from different number systems and outputs the result in the desired number system.
You call it like that:
java Calculator <operator> <number> <base> <otherNumber> <base> (solutionBase)
Unfortunately it does not work with floating point numbers.
Example:
$java Calculator + 5234 7 FABCD43 16 3
200022201200110011
My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?
public class Calculator {
public static void main(String args) {
// display usage if user wants so
if (args[0].contains("help")) {
displayHelp();
return;
}
// parse arguments
String operator = args[0];
String number1 = args[1];
int baseOfNumber1 = Integer.parseInt(args[2]);
String number2 = args[3];
int baseOfNumber2 = Integer.parseInt(args[4]);
int baseOfSolution = 0;
if (args.length == 6) {
baseOfSolution = Integer.parseInt(args[5]);
}
int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);
int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);
// calculate and print out
int solutionDec = 0;
if (operator.equals("+")) {
solutionDec = number1Dec + number2Dec;
} else if (operator.equals("-")) {
solutionDec = number1Dec - number2Dec;
} else if (operator.equals("x")) {
solutionDec = number1Dec * number2Dec;
} else if (operator.equals("/")) {
solutionDec = number1Dec / number2Dec;
}
if (args.length == 6) {
System.out.println(decimalToRandomBase(solutionDec,
baseOfSolution));
} else {
System.out.println(solutionDec);
}
}
private static int randomBaseToDecimal(String number, int base) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
result = base * result + digit;
}
return result;
}
// works only till base 16
private static String decimalToRandomBase(int number, int base) {
StringBuilder finalNumber = new StringBuilder();
while (number != 0) {
if ((number % base) > 9) {
switch ((number % base)) {
case 10: finalNumber.append("A"); break;
case 11: finalNumber.append("B"); break;
case 12: finalNumber.append("C"); break;
case 13: finalNumber.append("D"); break;
case 14: finalNumber.append("E"); break;
case 15: finalNumber.append("F"); break;
}
} else {
finalNumber.append(number % base);
}
number = number / base;
}
return new StringBuilder(finalNumber).reverse().toString();
}
private static void displayHelp() {
System.out.println("This program calculates with numbers of different bases");
System.out.println("Example: ");
System.out.println("java Calculator + 34 5 554 6");
System.out.println("You can also specify the base of the output number as the last argument:");
System.out.println("java Calculator + 34 5 554 6 2");
}
}
java calculator number-systems
add a comment |
This program calculates with numbers from different number systems and outputs the result in the desired number system.
You call it like that:
java Calculator <operator> <number> <base> <otherNumber> <base> (solutionBase)
Unfortunately it does not work with floating point numbers.
Example:
$java Calculator + 5234 7 FABCD43 16 3
200022201200110011
My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?
public class Calculator {
public static void main(String args) {
// display usage if user wants so
if (args[0].contains("help")) {
displayHelp();
return;
}
// parse arguments
String operator = args[0];
String number1 = args[1];
int baseOfNumber1 = Integer.parseInt(args[2]);
String number2 = args[3];
int baseOfNumber2 = Integer.parseInt(args[4]);
int baseOfSolution = 0;
if (args.length == 6) {
baseOfSolution = Integer.parseInt(args[5]);
}
int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);
int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);
// calculate and print out
int solutionDec = 0;
if (operator.equals("+")) {
solutionDec = number1Dec + number2Dec;
} else if (operator.equals("-")) {
solutionDec = number1Dec - number2Dec;
} else if (operator.equals("x")) {
solutionDec = number1Dec * number2Dec;
} else if (operator.equals("/")) {
solutionDec = number1Dec / number2Dec;
}
if (args.length == 6) {
System.out.println(decimalToRandomBase(solutionDec,
baseOfSolution));
} else {
System.out.println(solutionDec);
}
}
private static int randomBaseToDecimal(String number, int base) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
result = base * result + digit;
}
return result;
}
// works only till base 16
private static String decimalToRandomBase(int number, int base) {
StringBuilder finalNumber = new StringBuilder();
while (number != 0) {
if ((number % base) > 9) {
switch ((number % base)) {
case 10: finalNumber.append("A"); break;
case 11: finalNumber.append("B"); break;
case 12: finalNumber.append("C"); break;
case 13: finalNumber.append("D"); break;
case 14: finalNumber.append("E"); break;
case 15: finalNumber.append("F"); break;
}
} else {
finalNumber.append(number % base);
}
number = number / base;
}
return new StringBuilder(finalNumber).reverse().toString();
}
private static void displayHelp() {
System.out.println("This program calculates with numbers of different bases");
System.out.println("Example: ");
System.out.println("java Calculator + 34 5 554 6");
System.out.println("You can also specify the base of the output number as the last argument:");
System.out.println("java Calculator + 34 5 554 6 2");
}
}
java calculator number-systems
This program calculates with numbers from different number systems and outputs the result in the desired number system.
You call it like that:
java Calculator <operator> <number> <base> <otherNumber> <base> (solutionBase)
Unfortunately it does not work with floating point numbers.
Example:
$java Calculator + 5234 7 FABCD43 16 3
200022201200110011
My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?
public class Calculator {
public static void main(String args) {
// display usage if user wants so
if (args[0].contains("help")) {
displayHelp();
return;
}
// parse arguments
String operator = args[0];
String number1 = args[1];
int baseOfNumber1 = Integer.parseInt(args[2]);
String number2 = args[3];
int baseOfNumber2 = Integer.parseInt(args[4]);
int baseOfSolution = 0;
if (args.length == 6) {
baseOfSolution = Integer.parseInt(args[5]);
}
int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);
int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);
// calculate and print out
int solutionDec = 0;
if (operator.equals("+")) {
solutionDec = number1Dec + number2Dec;
} else if (operator.equals("-")) {
solutionDec = number1Dec - number2Dec;
} else if (operator.equals("x")) {
solutionDec = number1Dec * number2Dec;
} else if (operator.equals("/")) {
solutionDec = number1Dec / number2Dec;
}
if (args.length == 6) {
System.out.println(decimalToRandomBase(solutionDec,
baseOfSolution));
} else {
System.out.println(solutionDec);
}
}
private static int randomBaseToDecimal(String number, int base) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
result = base * result + digit;
}
return result;
}
// works only till base 16
private static String decimalToRandomBase(int number, int base) {
StringBuilder finalNumber = new StringBuilder();
while (number != 0) {
if ((number % base) > 9) {
switch ((number % base)) {
case 10: finalNumber.append("A"); break;
case 11: finalNumber.append("B"); break;
case 12: finalNumber.append("C"); break;
case 13: finalNumber.append("D"); break;
case 14: finalNumber.append("E"); break;
case 15: finalNumber.append("F"); break;
}
} else {
finalNumber.append(number % base);
}
number = number / base;
}
return new StringBuilder(finalNumber).reverse().toString();
}
private static void displayHelp() {
System.out.println("This program calculates with numbers of different bases");
System.out.println("Example: ");
System.out.println("java Calculator + 34 5 554 6");
System.out.println("You can also specify the base of the output number as the last argument:");
System.out.println("java Calculator + 34 5 554 6 2");
}
}
java calculator number-systems
java calculator number-systems
edited 5 hours ago
200_success
128k15150412
128k15150412
asked 6 hours ago
Dexter Thorn
627825
627825
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
This is my first post here and apologies if I made any blunders in my post or did something wrong.
Main feedback has already been given by AJNEufeld and this post is not about the performance of your program but rather other aspects.
You should try putting a check before you access an index in an array and slightly change your if block from this,
if (args[0].contains("help")) {
to,
if (args.length == 0 || args[0].contains("help") || args.length < 5) {
As the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.
Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.
These checks should make the program a little more safer.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
If your goal is to implement the conversion functions yourself, you can ignore this.
You can replace randomBaseToDecimal and decimalToRandomBase with:
Integer.parseInt(str, radix)- string to int with arbitrary base, and
Integer.toString(i, radix)- int to string with arbitrary base
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210316%2fcalculate-with-numbers-from-different-number-systems%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
This is my first post here and apologies if I made any blunders in my post or did something wrong.
Main feedback has already been given by AJNEufeld and this post is not about the performance of your program but rather other aspects.
You should try putting a check before you access an index in an array and slightly change your if block from this,
if (args[0].contains("help")) {
to,
if (args.length == 0 || args[0].contains("help") || args.length < 5) {
As the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.
Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.
These checks should make the program a little more safer.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
This is my first post here and apologies if I made any blunders in my post or did something wrong.
Main feedback has already been given by AJNEufeld and this post is not about the performance of your program but rather other aspects.
You should try putting a check before you access an index in an array and slightly change your if block from this,
if (args[0].contains("help")) {
to,
if (args.length == 0 || args[0].contains("help") || args.length < 5) {
As the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.
Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.
These checks should make the program a little more safer.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
This is my first post here and apologies if I made any blunders in my post or did something wrong.
Main feedback has already been given by AJNEufeld and this post is not about the performance of your program but rather other aspects.
You should try putting a check before you access an index in an array and slightly change your if block from this,
if (args[0].contains("help")) {
to,
if (args.length == 0 || args[0].contains("help") || args.length < 5) {
As the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.
Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.
These checks should make the program a little more safer.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
This is my first post here and apologies if I made any blunders in my post or did something wrong.
Main feedback has already been given by AJNEufeld and this post is not about the performance of your program but rather other aspects.
You should try putting a check before you access an index in an array and slightly change your if block from this,
if (args[0].contains("help")) {
to,
if (args.length == 0 || args[0].contains("help") || args.length < 5) {
As the former will run into ArrayIndexOutOfBoundsException if no argument is passed. Also it would be helpful to call the displayHelp() method in case no argument (args.length == 0) was passed so the user knows the usage of program.
Also, for safely accessing array indexes, you should put another OR condition args.length < 5 which will ensure at least five parameters are passed, else again you may run into ArrayIndexOutOfBoundsException.
These checks should make the program a little more safer.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 5 hours ago
Pushpesh Kumar Rajwanshi
1212
1212
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Pushpesh Kumar Rajwanshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
If your goal is to implement the conversion functions yourself, you can ignore this.
You can replace randomBaseToDecimal and decimalToRandomBase with:
Integer.parseInt(str, radix)- string to int with arbitrary base, and
Integer.toString(i, radix)- int to string with arbitrary base
add a comment |
If your goal is to implement the conversion functions yourself, you can ignore this.
You can replace randomBaseToDecimal and decimalToRandomBase with:
Integer.parseInt(str, radix)- string to int with arbitrary base, and
Integer.toString(i, radix)- int to string with arbitrary base
add a comment |
If your goal is to implement the conversion functions yourself, you can ignore this.
You can replace randomBaseToDecimal and decimalToRandomBase with:
Integer.parseInt(str, radix)- string to int with arbitrary base, and
Integer.toString(i, radix)- int to string with arbitrary base
If your goal is to implement the conversion functions yourself, you can ignore this.
You can replace randomBaseToDecimal and decimalToRandomBase with:
Integer.parseInt(str, radix)- string to int with arbitrary base, and
Integer.toString(i, radix)- int to string with arbitrary base
answered 5 hours ago
AJNeufeld
4,262318
4,262318
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210316%2fcalculate-with-numbers-from-different-number-systems%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown