I'm a java beginner trying to make a calculator that can accept mixed numbers and fractions, but rather than calculating the values it's just combining the two. (ex.1 + 1/2
The answer is 11/2
)` import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Woith = new Scanner(System.in);
System.out.println("Welcome to the Calc-O-Lator 9000\nthis calculator is able to\nadd, subtract, mulitiple, divide, and handle exponents of\nFRACTIONS\n\nenter 'quit' when done");
System.out.println("To input a mixed number use an underscore in addition with a slash(ex. 2_1/2), also provide a space between the first number and operator\n and the operator and the second number.");
Boolean on=true;
Scanner console=new Scanner(System.in);String firstNumber = Woith.next();
if (firstNumber.equals("quit")) {
on = false;
System.out.println("goodbye");
} else {
firstNumber = parseFullNumber(firstNumber);
}
String operator = Woith.next();
if (operator.equals("quit")) {
on = false;
System.out.println("goodbye");
} else if (operator.equals("+") || operator.equals("-") || operator.equals("/") || operator.equals("*")) {
} else {
throw new ArithmeticException();
}
String secondNumber = Woith.next();
if (secondNumber.equals("quit")) {
on = false;
System.out.println("goodbye");
} else {
secondNumber = parseFullNumber(secondNumber);
}
int wholeNumber = 0;
int numerator = 0;
int denominator = 0;
System.out.println(calculate(operator , firstNumber, secondNumber, wholeNumber, numerator, denominator));
}
public static String parseFullNumber(String input) {
int wholeNumber = 0;
int numerator = 0;
int denominator = 0;
int underscoreIdx = input.indexOf('_');
int slashIdx = input.indexOf('/');
if (underscoreIdx > -1) {
wholeNumber = Integer.parseInt(input.substring(0, underscoreIdx));
numerator = Integer.parseInt(input.substring(underscoreIdx + 1, slashIdx));
denominator = Integer.parseInt(input.substring(slashIdx + 1, input.length()));
} else {
if (slashIdx > -1) {
numerator = Integer.parseInt(input.substring(0, slashIdx));
denominator = Integer.parseInt(input.substring(slashIdx + 1, input.length()));
} else {
wholeNumber = Integer.parseInt(input);
}
}
return reduce(wholeNumber, numerator, denominator);
}
public static String reduce(int wholeNumber, int numerator, int denominator) {
int absNumerator = Math.abs(numerator);
if (absNumerator > 1) {
int commonFactor = 1;
for (int i = 2; i < Math.min(absNumerator, denominator); i++) {
if (numerator % i == 0 && denominator % i == 0) {
commonFactor = i;
}
}
numerator /= commonFactor;
denominator /= commonFactor;
}
if (absNumerator > denominator) {
int reduction = numerator / denominator;
if (wholeNumber >= 0) {
wholeNumber += reduction;
} else {
wholeNumber -= reduction;
}
numerator %= denominator;
}
if (wholeNumber != 0) {
if (numerator != 0) {
return wholeNumber + "_" + numerator + "/" + denominator;
} else {
return String.valueOf(wholeNumber);
}
} else {
if (numerator != 0) {
return numerator + "/" + denominator;
} else {
return String.valueOf(0);
}
}
}
public static String calculate(String input, String firstNumber,String secondNumber,int wholeNumber,int numerator,int denominator){
if (input.contains ("+"))
{
if(!input.contains("/")){
return ("The answer is "+firstNumber + secondNumber);
}
if (input.contains("/")){
return ("The answer is "+(numerator*denominator)+(numerator*denominator)+"/"+(numerator*denominator));
}
if(input.contains("_")){
return ("The answer is "+wholeNumber+numerator+"/"+denominator);
}
if(input.contains("-")){
if(!input.contains("/")){
return ("The answer is "+firstNumber + secondNumber);
}
if (input.contains("/")){
return ("The answer is "+(numerator*denominator)+"/"+(numerator*denominator));
}
if(input.contains("_")){
return ("The answer is "+wholeNumber+numerator+"/"+denominator);
}
if(input.contains("*")){
if(!input.contains("/")){
return ("The answer is "+firstNumber + secondNumber);
}
if (input.contains("/")){
return ("The answer is "+(numerator*numerator)+"/"+(denominator*denominator));
}
if(input.contains("_")){
return ("The answer is "+wholeNumber+numerator+"/"+denominator);
}
}
}
}
return input;
}
}
Well, other problems from your code aside, your problem "1 + 1/2 The answer is 11/2" originates from here:
if (input.contains("/")){
return ("The answer is "+(numerator*denominator)+(numerator*denominator)+"/"+(numerator*denominator));
}
The output you stated is correct as that is string concatenation. You really want float conversion, so try this instead:
if (input.contains("/")) {
return ("The answer is "+(numerator*denominator)+((float)(numerator*denominator)/(numerator*denominator)));
}
This is because you used "+" opeartion for the String values.
e.g.
The firstNumber is a type of String, like "1"
The secondNumber is a type of String, like "1/2"
In calculate method, You print answer using the following way
if(!input.contains("/")){
return ("The answer is "+firstNumber + secondNumber);
}
Here will return a string value of "
The answer is 11/2"
That's what you are encountering (ex.1 + 1/2 The answer is 11/2)
Related
I'm trying to write a program that reduces Fractions to their simplest form but it is only partially working (simplifying the numerator by the proper amount but leaving the denominator the same), can somebody help me understand what is failing?
private int greatestCommonDivisor(int num1, int num2) {
while(num1-num2!=0) {
if(num1>num2) {
num1 = num1 - num2;
}
else {
num2 = num2 - num1;
}
}
return num1;
}
private void simplify() {
if(denominator<0) {
numerator = numerator*(-1);
denominator = denominator*(-1);
}
else {
numerator = numerator/greatestCommonDivisor(numerator, denominator);
denominator = denominator/greatestCommonDivisor(numerator, denominator);
}
}
public String toString() {
simplify();
if(denominator == 1) {
return numerator + "";
}
else if(numerator!=0) {
return numerator + "/" + denominator;
}
else {
return "0";
}
}
I believe that is all the necessary information, definitely let me know if you need something else.
Sorry if this is a simple error, I am still very new to Java and have trouble with all the rules. I am trying to create a calculator that takes in roman numerals, converts them to integers, them performs operations with them, and then converts them back roman numerals to print by calling methods. I put this together looking at some examples and it seems to almost all work out except for the convertFromRoman method. If anyone sees any other errors please let me know because I really feel lost. Heres the code:
package roman_calculator;
import java.util.Scanner;
public class RomanCalculator {
public static Scanner kbInput = new Scanner(System.in);
public static String doMath(char operator, int firstNum, int secondNum) {
switch (operator) {
case '+':
return convertToRoman(firstNum + secondNum);
case '-':
return convertToRoman(firstNum - secondNum);
case '*':
return convertToRoman(firstNum * secondNum);
case '/':
return convertToRoman(firstNum / secondNum);
}
return "omething";
/*
* This method will perform the arithmetic
* indicated by the operator (+ -* /),
* invoke convertToRoman to convert answer to Roman number,
* then return answer
* */
}
public static char getOperator() {
System.out.println("please choose an operator: +, - , * , or /");
return kbInput.next().charAt(0);
}
public static int getOperands(int which) {
while (true) {
System.out.print("Enter operand" + ": ");
String roman = kbInput.nextLine().toUpperCase();
int romanNum = convertFromRoman(roman);
if (romanNum >= 0)
return romanNum;
else
System.out.println("Bad operand, please try again");
/*This routine should prompt the user to enter Roman number.
convertFromRoman needs to be invoked to convert the Roman number to an integer.
If the input is invalid (-1 returned from convertFromRoman)
then complain and prompt the user again.
*/
}
public static int convertFromRoman(String roman) {
int result = 0;
for (int i = 0; i < roman.length(); i++) {
int s1 = num(roman.charAt(i));
if (s1 < 0) {
System.out.println("Invalid operand");
}
if (i + 1 < roman.length()) {
int s2 = num(roman.charAt(i + 1));
if (s2 < 0) {
System.out.println("Invalid operand");
}
if (s1 >= s2) {
result = result + s1;
} else {
result = result + s2 - s1;
i++;
}
} else {
result = result + s1;
i++;
}
}
return result;
}
/*
* This method will convert Roman number to integer
* return -1 when input is invalid
*
* */
}
public static String convertToRoman(int num) {
System.out.println(num);
String roman = "";
while (num > 0) {
while (num >= 1000) {
roman = roman + "M";
num -= 1000;
}
while (num >= 500) {
roman = roman + "M";
num -= 500;
}
while (num >= 100) {
roman = roman + "D";
num -= 100;
}
while (num >= 50) {
roman = roman + "C";
num -= 50;
}
while (num >= 10) {
roman = roman + "X";
num -= 10;
}
while (num >= 5) {
roman = roman + "V";
num -= 5;
}
while (num >= 1) {
roman = roman + "I";
num -= 1;
}
}
return roman;
}
static int num (char r) {
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
/*
* This method will convert integer to Roman number
* */
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String result;
do {
result = doMath(getOperator(), getOperands(), getOperands());
System.out.println(result);
System.out.println("do you want to continue? y/n");
kbInput.nextLine();
} while (kbInput.nextLine().charAt(0) == 'y');
System.out.println("Have a nice day!");
}
}
You have a missing } in the following code, the last } was missing.
public static int getOperands(int which) {
while (true) {
System.out.print("Enter operand" + ": ");
String roman = kbInput.nextLine().toUpperCase();
int romanNum = convertFromRoman(roman);
if (romanNum >= 0)
return romanNum;
else
System.out.println("Bad operand, please try again");
}
}
And you need to remove the last } from the methode convertFromRoman.
Also there is a error in the line result = doMath(getOperator(), getOperands(), getOperands()); where you either need to pass a parameter to getOperands() or change the method signiture to getOperator() or whatever you are trying.
A tip for you: Formating your code makes it easier to read and see the layers (e.g for Eclispe IDE is it Ctrl + Shift + F)
I have a class runner that is supposed to do the keep it change it flip it method when doing fractions.
public class Fraction2
{
private int numerator = 0;
private int denominator = 1;
public Fraction2()
{
numerator = 0;
denominator = 1;
}
public Fraction2(int num, int denom)
{
numerator = num;
denominator = denom;
}
public void show(int num, int denom)
{
System.out.println(numerator + "/" + denominator);
}
public String toString()
{
return (numerator + "/" + denominator);
}
public Fraction2 mult(Fraction2 temp)
{
return new Fraction2(this.numerator * temp.numerator,
this.denominator * temp.denominator);
}
public Fraction2 add(Fraction2 sent)
{
int cmmndenom = sent.denominator * this.denominator;
int answer = this.numerator * sent.denominator + sent.numerator * this.denominator;
return new Fraction2(answer, cmmndenom);
}
public Fraction2 divide(Fraction2 sent)
{
//keep it change it flip it method
Fraction2 answer = new Fraction2(this.numerator * sent.denominator,
this.denominator * sent.numerator);
return answer;
}
public Fraction2 reduce()
{
int ansNumer = numerator;
int ansDenom = denominator;
for (int i = 1; ((i <= (numerator)) && i <= (denominator)); i++)
{
if (((numerator % i) == 0) && ((denominator % i) == 0))
{
ansNumer = numerator / i;
ansDenom = denominator / i;
}
}
return new Fraction2(ansNumer, ansDenom);
}
}
When I put in 1/4 and 2/6 and I should be getting 6/8 but I'm getting 8/6. The rest of the methods work except for the dividing part. I'm just stuck on how to get 6/8 instead of 8/6.
import java.util.Scanner;
public class FractionTesterv2
{
public static void main(String args[])
{
System.out.println("\f");
Scanner input = new Scanner(System.in);
int numerator;
int denominator;
int addCount = 0;
int multCount = 0;
int divCount = 0;
//***************************************
//Creating future objects
Fraction2 fraction3 = new Fraction2();
Fraction2 addAnswer = new Fraction2();
Fraction2 multAnswer = new Fraction2();
Fraction2 divAnswer = new Fraction2();
//***************************************
System.out.println("Enter a numerator");
numerator = input.nextInt();
System.out.println("Enter a denominator");
denominator = input.nextInt();
//creates first fraction
Fraction2 fraction2 = new Fraction2(numerator, denominator);
System.out.println("would you like to add another fraction?");
String choice = input.nextLine();
choice = input.nextLine();
// Will only display first fraction entered
if (choice.equals("no"))
System.out.println(fraction2);
else
{
while (!(choice.equals("no")))
{
System.out.println("Enter a numerator");
numerator = input.nextInt();
System.out.println("Enter a denominator");
denominator = input.nextInt();
fraction3 = new Fraction2(numerator, denominator);
//***************************************
//Adding Fractions
if (addCount == 0)
addAnswer = fraction2;
addCount = 1;
addAnswer = fraction3.add(addAnswer);
System.out.println("add: " + addAnswer);
//***************************************
//Multiplying Fractions
if (multCount == 0)
multAnswer = fraction2;
multCount = 1;
multAnswer = fraction3.mult(multAnswer);
System.out.println("Multiply: " + multAnswer);
//***************************************
//Dividing Fractions
if (divCount == 0)
divAnswer = fraction2;
divCount = 1;
divAnswer = fraction3.divide(divAnswer);
System.out.println("Divide: " + divAnswer);
//***************************************
System.out.println("would you like to add another Fraction?");
choice = input.nextLine();
choice = input.nextLine();
}
Fraction2 addReduced = addAnswer.reduce();
Fraction2 multReduced = multAnswer.reduce();
Fraction2 divReduced = divAnswer.reduce();
System.out.println("Adding Reduced: " + addReduced);
System.out.println("Multiply Reduced: " + multReduced);
System.out.println("Dividing Reduced: " + divReduced);
}
}
}
My code is fairly large to start and I'm sure I can figure out how to simplify it. Just looking for help on the one part.
The first two numbers that you enter ("1", "4") are used to build fraction2.
The next two numbers ("2", "6") are used to build fraction3.
And then you calculate:
divAnswer = fraction3.divide(fraction2);
"2/6" divided by "1/4" is "8/6" - if you want "6/8" then you would have to calculate "1/4" divded by "2/6", which would be
divAnswer = fraction2.divide(fraction3);
For chained division operations you could write
// this shows an extract of a larger fraction of your code!
divAnswer = fraction2;
while (!(choice.equals("no")))
//...
// no need for some strange divCount flag here
divAnwser = divAnswer.divide(fraction3);
//...
}
or, similar to what your doing now:
while (!(choice.equals("no")))
//...
if (divCount == 0)
divAnswer = fraction2;
divCount = 1;
divAnswer = divAnswer.divide(fraction3);
//...
}
The basic problem is that your current code has the division operations swapped and that is what I tried to show.
I've been working on a program that is supposed to analyze a credit card number that the user enters in, including info regarding its company, whether it is valid or not, and so on.
My issue is that I continue to run the NoSuchElementException, and from what I have read it seems that one of my loops continues to run, but I'm not sure where, or why.
import java.util.*;
public class CreditCard {
public static void main (String[] args) {
Scanner in = new Scanner (System.in);
long nums = 0;
int length;
System.out.print("Enter 15 or 16-digit credit card number: ");
long numsEntered = in.nextLong();
if(isValid(nums) == true) {
System.out.println(nums + " is valid.");
} else {
System.out.println(nums + " is invalid.");
}
}
public static boolean isValid (long cc_num) {
long numsEntered;
int total = sumOfOdd(cc_num) + sumOfEven(cc_num);
return (total % 10 == 0) && (prefixMatched(cc_num, 1) == true) &&
(getSize(cc_num)>=13) && (getSize(cc_num)<=16);
}
public static int sumOfEven(long number) {
int doubleEven = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubleEven += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubleEven;
}
public static int sumOfOdd(long number) {
int odd = 0;
while (number <=9) {
odd += (int)(number % 10);
number = number % 100;
}
return odd;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstNum = number % 10;
int secondNum = (int)(number / 10);
return firstNum + secondNum;
}
}
public static boolean prefixMatched(Long number, int d) {
if((getPrefix(number, d) == 3) || (getPrefix(number, d) == 4) || (getPrefix(number, d) == 5)) {
if(getPrefix(number, d) == 3) {
System.out.println("Visa");
} else if (getPrefix(number, d) == 3) {
System.out.println("Amex");
} else if (getPrefix(number, d) == 5) {
System.out.println("Master Card");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d >0) {
d = d/10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if(getSize(number) < k) {
return number;
} else {
int size = (int)getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
The exact error i continue to get is:
Enter 15 or 16-digit credit card number: Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextLong(Scanner.java:2222)
at java.util.Scanner.nextLong(Scanner.java:2182)
at CreditCard.main(CreditCard.java:11)
Well, you are calling isValid with num. Shouldn't you call isValid with numsEntered instead?
I'm new to Java programming. I am trying to make a Fraction Calculator but when I try to run the program it gives me an error. The error is with the Switch statements but I don't know what happened.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Welcome to My FracCalc");
boolean continueProcessing = true;
while (continueProcessing) {
System.out.println("Type an expression and press <enter>");
String Operand1 = console.next();
if (Operand1.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else {
Operand1 = parseFullNumber(Operand1);
}
String Operator = console.next();
if (Operator.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else if (Operator.equals("+") || Operator.equals("-") || Operator.equals("/") || Operator.equals("*")) {
} else {
throw new ArithmeticException();
}
String Operand2 = console.next();
if (Operand2.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else {
Operand2 = parseFullNumber(Operand2);
}
System.out.println( Operand1 + " " + Operator + " " + Operand2);
//System.out.println("First Fraction is: " + Operand1);
//System.out.println("Operator is: " + Operator);
//System.out.println("Second Fraction is: " + Operand2);
float answer;
System.out.println(Operator);
switch (Operator) {
case "+":
answer = Operand1 + Operand2;
break;
case "-":
answer = Operand1 - Operand2;
break;
case "*":
answer = Operand1 * Operand2;
break;
case "/":
answer = Operand1 / Operand2;
break;
}
}
}
public static String parseFullNumber(String input) {
int wholeNumber = 0;
int numerator = 0;
int denominator = 0;
;
int underscoreId = input.indexOf('_');
int slashId = input.indexOf('/');
// Check for underscore "_" //
if (underscoreId > -1) {
wholeNumber = Integer.parseInt(input.substring(0, underscoreId));
numerator = Integer.parseInt(input.substring(underscoreId + 1, slashId));
denominator = Integer.parseInt(input.substring(slashId + 1, input.length()));
} else {
if (slashId > -1) {
// no underscore but there is a slash //
numerator = Integer.parseInt(input.substring(0, slashId));
denominator = Integer.parseInt(input.substring(slashId + 1, input.length()));
} else {
// there is no underscore or slash //
wholeNumber = Integer.parseInt(input);
}
}
return simplify(wholeNumber, numerator, denominator);
}
//simplifying fractions //
public static String simplify(int wholeNumber, int numerator, int denominator) {
// absolute values //
int absNumerator = Math.abs(numerator);
// factor if applicable //
if (absNumerator > 1) {
int commonFactor = 1;
for (int i = 2; i < Math.min(absNumerator, denominator); i++) {
if (numerator % i == 0 && denominator % i == 0) {
commonFactor = i;
}
}
numerator /= commonFactor;
denominator /= commonFactor;
}
// reduce if applicable //
if (absNumerator > denominator) {
int reduction = numerator / denominator;
if (wholeNumber >= 0) {
wholeNumber += reduction;
} else {
wholeNumber -= reduction;
}
numerator %= denominator;
}
// prints //
if (wholeNumber != 0) {
if (numerator != 0) {
return wholeNumber + "_" + numerator + "/" + denominator;
} else {
return String.valueOf(wholeNumber);
}
} else {
if (numerator != 0) {
return numerator + "/" + denominator;
} else {
return String.valueOf(0);
}
}
}
}
Here is the error i got:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Type mismatch:
cannot convert from String to float The operator - is undefined for the argument type(s) java.lang.String, java.lang.String
The operator * is undefined for the argument type(s) java.lang.String, java.lang.String
The operator / is undefined for the argument type(s) java.lang.String, java.lang.String
at FracCalcApp.main(FracCalcApp.java:53)
Operand1 and Operand2 are String(s). You need to parse them before you can perform arithmetic. Something like,
double answer;
System.out.println(Operator);
switch (Operator) {
case "+":
answer = Double.valueOf(Operand1) + Double.valueOf(Operand2);
break;
case "-":
answer = Double.valueOf(Operand1) - Double.valueOf(Operand2);
break;
case "*":
answer = Double.valueOf(Operand1) * Double.valueOf(Operand2);
break;
case "/":
answer = Double.valueOf(Operand1) / Double.valueOf(Operand2);
break;
}
Finally, by convention, Java variables should start with a lower case letter; operand1, operand2 and operator.
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
float a = sc.nextFloat();
System.out.println("Enter second number");
float b = sc.nextFloat();
System.out.println("choose your operation");
char operator = sc.next().charAt(0);
float answer;
switch (operator){
case '+' :
answer = a +b;
System.out.println("Answer:"+answer);
break;
case '-' :
answer = a-b;
System.out.println("Answer:"+answer);
break;
case '*' :
answer = a*b;
System.out.println("Answer:"+answer);
break;
default:
answer = a/b;
System.out.println("Answer:"+answer);
}
}