Command Line Calulator, Java - java

Input from the Java commandline: "4 + 6 + 5 - 5".
Wanted outcome: "is 10".
Actual outcome: "is 5".
class Calculator
{
int v_in1, v_in2, v_in3, v_in4, v_answer, result;
String v_sign1, v_sign2, v_sign3;
public Calculator()
{
}
public void count(String[] args)
{
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+": {
v_answer += v_in1;
break;
}
case "-": {
v_answer -= v_in1;
break;
}
}
}
System.out.print("is " + v_answer);
}
}
There might be some additional problems e.g too many variable declared etc, but what I'm concerned about it the for- if- switch part, I'm unable to pin- point the problem.
Thank you :)

The problem is that you are applying the operation to the previous number, not to the next to come. Instead you should memorize the operator and update the result when you see a number, e.g. like this:
int sign = +1, result = 0;
for (String arg : args) {
switch (arg) {
case "+":
sign = +1;
break;
case "-":
sign = -1;
break;
default:
result += sign * Integer.parseInt(arg);
}
}

This is happening because your last integer wont be taken into account as it is just stored in v_in1, but since there is no +,- so it doesnt get added or subtracted. Try this:
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+":
{
v_answer = v_in1 + Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
case "-":
{
v_answer = v_in1 - Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
}
}

I do not know all requirements for this task, but I recommend to convert the whole expression to postfix notation, then parse it using stack to evaluate the result.

I took a look at your method, and I recommend you simplify your code (something like this for long count(String[] args))
long result = 0; // Note, this shadows your Object's result. I'm not sure why you
// had hard-coded fields like that. I don't think you need them.
// Also, this returns a long.
boolean negative = false;
for (String arg : args) {
String oper = arg.trim();
if (oper.equals("+")) { // Is it a plus sign?
negative = false;
} else if (oper.equals("-")) { // Is it a minus sign?
negative = !negative; // - a negative value is addition
} else {
try {
int i = Integer.parseInt(oper); // Parse the integer
if (negative) {
i = -i;
negative = false;
}
result += i; // add the result
} catch (NumberFormatException nfe) {
System.err.println(oper + " is not +, - or a number");
}
}
}
return result;

This is what worked in the exercise.
class Calculator
{
int v_answer = 0;
int v_in1 = 0;
public Calculator()
{
}
public void count(String args[])
{
System.out.println();
System.out.print("Result of the calculation ");
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]+ " ");
if(i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
}
if(i == 0)
{
v_answer += Integer.parseInt(args[0]);
}
if(args[i].equals("+"))
{
v_answer += Integer.parseInt(args[i+1]);
}
else if(args[i].equals("-"))
{
v_answer -= Integer.parseInt(args[i+1]);
}
}
System.out.print("is " + v_answer);
System.out.println();
}
}

Related

Making an Armstrong number checker but if condition is not working

I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}

Transforming a string to an integer

What i am striving to achieve: Given a simple equation, you should output the correct value for variable "x". The equation has two numbers greater than 0 and variable "x", and between these can be "+", "-" or "=". Numbers, variable "x", symbols "+", "-", "=" all separated by a space.
the problem: when i read the numbers they come out as strings instead of integers
I am very new to codeing and tried this but i don't get why when i use var and input a number it reads it as a string instead of an integer
import java.util.*;
public class Main {
public static void main(String[] args) {
int outpt;
Scanner scanner = new Scanner(System.in);
var sig1 = scanner.next();
var sig2 = scanner.next();
var sig3 = scanner.next();
var sig4 = scanner.next();
var sig5 = scanner.next();
if(sig2 == "=")
{
if(sig1 == (int)sig1)
{
if(sig3 == (int)sig3)
{
if(sig4 == "-")
{
outpt = sig3 - sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig3;
System.out.println("");
System.out.println(outpt);
}
}
else
{
if(sig4 == "-")
{
outpt = sig5 + sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig4 == "-")
{
outpt = sig3 - sig5;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig3 + sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig5 == (int)sig5)
{
if(sig1 == (int)sig1)
{
if(sig2 == "+")
{
outpt = sig5 - sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig5;
System.out.println("");
System.out.println(outpt);
}
}
else
{
if(sig2 == "+")
{
outpt = sig5 - sig3;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig3 + sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig2 == "+")
{
outpt = sig1 + sig3;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig3;
System.out.println("");
System.out.println(outpt);
}
}
}
}
}
Sample Input 1:
5 + x = 15
Sample Output 1:
10
Sample Input 2:
x - 8 = 10
Sample Output 2:
18
Sample Input 3:
x = 20 - 15
Sample Output 3:
5
Instead of using 100 if statements try this. In my code I am taking whole equation as input and storing it in array and then saving the position of symbols and numbers in variables which I can later use the decide what operation I should perform
Here is the code
import java.util.Scanner;
public class AlgebraEquation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the whole equation: ");
String equation = scan.nextLine();
scan.close();
String[] equationSplit = equation.split(" ");
// This code block is just to show how logic is working
for (int i = 0; i < equationSplit.length; i++) {
System.out.print(equationSplit[i] + ", ");
}
System.out.println();
int xPosition = -1, const1Pos = -1, const2Pos = -1, equalPos = -1, operatorPos = -1;
// Checking each index of array and saving position of characters
for (int i = 0; i < equationSplit.length; i++) {
if (equationSplit[i].equalsIgnoreCase("X")) {
xPosition = i;
} else if (equationSplit[i].equals("=")) {
equalPos = i;
} else if (equationSplit[i].matches("[-+*/]")) { // If character matches any of these "-+*/"
operatorPos = i;
} else {
// Checking if const1Pos is filled or not
if (const1Pos < 0) {
const1Pos = i;
} else {
const2Pos = i;
}
}
}
// This code block is just to show how logic is working
System.out.println(equationSplit[xPosition] + " Position: " + xPosition);
System.out.println(equationSplit[equalPos] + " Position: " + equalPos);
System.out.println(equationSplit[operatorPos] + " Position: " + operatorPos);
System.out.println(equationSplit[const1Pos] + " Position: " + const1Pos);
System.out.println(equationSplit[const2Pos] + " Position: " + const2Pos);
String operator = equationSplit[operatorPos];
switch (operator) {
case "+":
System.out.println("Addition");
// Do you calculation based on relative position of equal, const1Pos, and
// const2Pos
break;
case "-":
System.out.println("Subtraction");
break;
case "*":
System.out.println("Multiplication");
break;
case "/":
System.out.println("Division");
break;
}
}
}
Output
Enter the whole equation: 5 + x = 8 //(Enter Key Pressed)
5, +, x, =, 8,
x Position: 2
= Position: 3
+ Position: 1
5 Position: 0
8 Position: 4
Addition
this is the final code it came to
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
String c = scanner.next();
String d = scanner.next();
String e = scanner.next();
if (b.equals("+") && a.equals("x")) {
System.out.println(Integer.parseInt(e) - Integer.parseInt(c));
} else if (b.equals("+") && c.equals("x")) {
System.out.println(Integer.parseInt(e) - Integer.parseInt(a));
} else if (b.equals("-") && a.equals("x")) {
System.out.println(Integer.parseInt(e) + Integer.parseInt(c));
} else if (b.equals("-") && c.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(e));
} else if (d.equals("+") && c.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(e));
} else if (d.equals("+") && e.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(c));
} else if (d.equals("-") && c.equals("x")) {
System.out.println(Integer.parseInt(a) + Integer.parseInt(e));
} else if (d.equals("-") && e.equals("x")) {
System.out.println(Integer.parseInt(c) - Integer.parseInt(a));
} else if (b.equals("+") && e.equals("x")) {
System.out.println(Integer.parseInt(c) + Integer.parseInt(a));
} else if (d.equals("+") && a.equals("x")) {
System.out.println(Integer.parseInt(c) + Integer.parseInt(e));
} else if (b.equals("-") && e.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(c));
} else if (d.equals("-") && a.equals("x")) {
System.out.println(Integer.parseInt(c) - Integer.parseInt(e));
}
}
}

Creating a Palindrome identifier

How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)

Why do I get a "String index out of range" error when I run this program?

I am creating a program that converts roman numeral input to it's integer value and every time I run the program I get an error that says,
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romannumeralconverter.RomanNumeralConverter.convert(RomanNumeralConverter.java:20)
at romannumeralconverter.RomanNumeralConverter.romanInput(RomanNumeralConverter.java:68)
at romannumeralconverter.RomanNumeralConverter.printValue(RomanNumeralConverter.java:72)
at romannumeralconverter.RomanNumeralConverter.main(RomanNumeralConverter.java:77)
Java Result: 1"
Now I am new to programming so I don't know what this means exactly. I am guessing my conversion algorithm is wrong in which the roman numeral entered is not read by the loop. Here is what I have:
public class RomanNumeralConverter {
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result;
}
public int romanInput() {
return convert(getUserInput());
}
public void printValue() {
System.out.println(romanInput());
}
public static void main (String[] args) {
new RomanNumeralConverter().printValue();
}
}
If my algorithm is wrong, does anyone know how to fix it?
change userInput.charAt(x); to userInput.charAt(x - 1);
charAt starts with index 0 to length -1
or int x = userInput.length() - 1;
#nd issue, everything coming out as 0
You are actually using uppercase characters in switch statement.
so just add below statement,in the starting of your function convert(String userInput)
userInput = userInput.toUpperCase(); // converts user input to uppercase , even if its is already or not.
code
public int convert(String userInput) {
userInput = userInput.toUpperCase();
int result = 0;
int subtractamount = 0;
int x = userInput.length() - 1;
while (x != 0) {
char romanConvert = userInput.charAt(x);
if (x >= 1) {
if (convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
output
Enter a roman numeral in uppercase: adig
Invalid character!
Invalid character!
Invalid character!
Invalid character!
501
You should start with
int x = userInput.length() - 1;
The last character in a string is at the index - (length-of-string - 1), not length-of-string.

Why is my program crashing (java)?

I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
switch(choice){
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
if (isValid) {
System.out.println(hex + " is valid");
}
break;
case 'n':
System.out.print("Quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
public static long convert (String hexValue) {
long decimal = 0;
boolean isNegative = false;
int a = 0;
if (hexValue.charAt(0) == '-') {
isNegative = true;
a = 1;
}
for (int i = a; i<hexValue.length(); i++) {
decimal = decimal*16;
if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
decimal += hexValue.charAt(i) - '0';
}
else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
decimal += hexValue.charAt(i) - 'a' + 10;
}
}
if (isNegative == true) {
decimal *= -1;
}
return decimal;
}
}
why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?
If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:
...
isValid = valid(hex);
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
...
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
int base = 10;
switch(choice)
{
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase(); //I'm not sure if this step is necessary
try {
Integer value = Integer.parseInt(hex, 16);
System.out.println("Valid hex format");
System.out.println("Hex: " + hex);
System.out.println("Decimal: " + value);
}
catch (NumberFormatException e) {
System.out.println("Invalid hex format");
System.out.println("Input: " + hex);
}
break;
case 'n':
System.out.print("Quit");
break
}
} while (choice != 'n');
Now you can delete all your helper methods
Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
else{
System.out.println("invalid");
}
Updated:
Change your valid method as follows:
public static boolean valid(String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i = a; i < validString.length(); i++) {
// if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
// return false;
// }
char ch=validString.charAt(i);
if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
return false;
}
}
return true;
}

Categories

Resources