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.
Related
I want to do a simple beginner project using methods, if statements, and user input. I am having an issue though with the calc() method. How can I return two different data types in java, and if I cannot, how could I do it, still by using more than the main method?
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
System.out.println(calc(num1,op,num2));
}
//troublesome part is here
public static double calc(double num1, String op, double num2){
if (op == "+") {
return (num1 + num2);
}
else if (op == "-") {
return (num1 - num2);
}
else if (op == "*") {
return (num1 * num2);
}
else if (op == "/") {
return (num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
}
you could generate a custom Exception, also you need to use the method .equals() inside the if validations, otherwise it is not going to work.
fourFunctionCalculator.java
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
try {
System.out.println(calc(num1,name,num2));
} catch (InvalidOperatorException e) {
System.out.println(e);
}
}
public static double calc(double num1, String op, double num2){
if (op.equals("+")) {
return (num1 + num2);
}
else if (op.equals("-")) {
return (num1 - num2);
}
else if (op.equals("*")) {
return (num1 * num2);
}
else if (op.equals("/")) {enter code here
return (num1 / num2);
}
throw new InvalidOperatorException("INVALID OPERATOR : " + op);
}
}
InvalidOperatorException.java
public class InvalidOperatorException
extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidOperatorException(String errorMessage) {
super(errorMessage);
}
}
I recommend returning an OptionalDouble object as placeholder of something valid or not...
Ex #1: return OptionalDouble.of(num1 + num2); // first if outcome
Ex #2: return OptionalDouble.empty(); // for the last else
Then your main(...) method needs to be something like...
System.out.println(calc(num1,op,num2).orElseThrow(() -> new IllegalArgumentException("INVALID OPERATOR")));
I suggest returning always String.
public static String calc(double num1, String op, double num2){
if (op == "+") {
return String.valueOf(num1 + num2);
}
else if (op == "-") {
return String.valueOf(num1 - num2);
}
else if (op == "*") {
return String.valueOf(num1 * num2);
}
else if (op == "/") {
return String.valueOf(num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
I designed a small program where I have three exam grades and I use the Grades class to compute the average of the three. Also, I prompt for the exam number (1,2, or 3) and it should return it. However, I keep getting 0.0 as the output for both the average exam score and chosen exam score.
package GradesClass;
import java.util.Scanner;
public class GradesDriver {
public static void main(String[] args) {
Grades school = new Grades(90.9,87.9,99.9);
Scanner in = new Scanner(System.in);
System.out.println("Enter desired test number: ");
int testnumber = in.nextInt();
System.out.println(school);
System.out.println("Exam score: " + school.getGrades(testnumber));
}
}
package GradesClass;
public class Grades {
private double num1, num2, num3;
private int testnumber;
private double average;
public Grades(double num1, double num2, double num3) {
num1 = 0;
num2 = 0;
num3 = 0;
}
public void setGrades(double scorenumber, int testnumber) {
if (testnumber == 1) {
num1 = scorenumber;
} else if (testnumber == 2) {
num2 = scorenumber;
} else {
num3 = scorenumber;
}
}
public double getGrades(int testnumber) {
if (testnumber == 1) {
return(num1);
} else if (testnumber == 2) {
return(num2);
} else {
return(num3);
}
}
public double average(double num1, double num2, double num3) {
average = ((num1+num2+num3)/3.0);
return(average);
}
public String toString() {
return("Average: " + average);
}
}
In your constructor for Grades you are setting the member variables to zero instead of the values supplied in the parameters. Change the constructor to
public Grades(double num1, double num2, double num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
I'm having difficulty understanding why this function is behaving incorrectly.
If I make the value of num1 10 and the value of num2 20, when run, the program tells me that 10 is a value of 20 when in fact it isn't. When I switch the values around and make num1 20 and num2 10, it tells me that num1 is a multiple of num2 - which is correct.
If anyone can explain to me where I'm going wrong and if they could show me a corrected version of the code (if possible), it would be greatly appreciated!
public class Multiple {
public static void main(String[]args) {
boolean multiple = true;
while(multiple = true) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if (result = true) {
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num2 + " is not a multiple of " + num1);
}
break;
}
}
public static boolean isMultiple(long x, long y) {
if (x % y == 0) {
return true;
} else if (y % x == 0) {
return false;
}
return false;
}
}
The line if (result = true) is actually setting result to true. It should be changed to result == true. I'm not sure about the purpose of the while loop, but I know that the isMultiple method can definitely be streamlined. Anyway, I corrected the if condition and did some other refactoring.
public class Multiple {
public static void main(String[] args) {
long num1 = 10;
long num2 = 20;
if (isMultiple(num1, num2)) {
System.out.println(num1 + " is a multiple of " + num2);
} else {
// num1 should come before num2 here
System.out.println(num1 + " is not a multiple of " + num2);
}
}
public static boolean isMultiple(long x, long y) {
// check that x is a multiple of y
return x % y == 0;
}
}
You code should be like :
public static void main(String[] args) {
boolean multiple = true;
while(multiple) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if(result){
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num1 + " is not a multiple of " + num2);
}
break;
}
}
public static boolean isMultiple(long x, long y){
if (y%x == 0) {
return true;
}
return false;
}
Changes = true in if and while is not needed. Also for the first num to be multiple of second you need to doe second num % first number. You don't need a loop but i think you have it cause you might want it later on so i'm keeping it.
public static void main(String[] args) {
boolean multiple = true;
while(multiple) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if(result){
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num1 + " is not a multiple of " + num2);
}
break;
}
}
public static boolean isMultiple(long x, long y){
if (x<y) return false;
return (x % y == 0);
}
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)
Im having problems with my program. the program displays the first JOption message dialog box, but when you input a value, it fails to display the second dialog box??
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"please enter the first number");
num1 = input.nextInt();
JOptionPane.showInputDialog(null,"please enter the second number");
num2 = input.nextInt();
JOptionPane.showInputDialog(null,"Please enter operation");
operation = input.next();
if (operation.equals ("+"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 + num2));
}
if (operation.equals ("-"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 - num2));
}
if (operation.equals ("/"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 / num2));
}
if (operation.equals ("*"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 * num2));
}
}
}
Read the numbers from the dialog output instead of from System.in:
String firstNumber = JOptionPane.showInputDialog(null,"please enter the first number");
if (firstNumber != null) {
num1 = Integer.parseInt(firstNumber);
}
Scanner is unnecessary in your code.
You can try using that sample code:
import javax.swing.JOptionPane;
public class Hw4_3 {
private static boolean flag;
public static void main(String[] args) {
do {
String[] expression = getTask();
double result = calculate(expression);
display(expression, result);
repeat();
} while (flag);
}
public static String[] getTask()
{
String bleh = JOptionPane.showInputDialog(null, "Please enter what you would like to calculate: ");
String[] tokens = bleh.split(" ");
return tokens;
}
public static double calculate(String[] data)
{
double num1 = Double.parseDouble(data[0]);
double num2 = Double.parseDouble(data[2]);
double result = 0;
if(data[1].equals("+"))
{
result = add(num1, num2);
return result;
}
else if(data[1].equals("-"))
{
result = subtract(num1, num2);
return result;
}
else if(data[1].equals("*"))
{
result = multiply(num1, num2);
return result;
}
else
{
if(num2 == 0)
{
JOptionPane.showMessageDialog(null, "Sytax error, divide by zero");
}
result = divide(num1, num2);
return result;
}
}
public static double add(double num1, double num2)
{
return num1 + num2;
}
public static double subtract(double num1, double num2)
{
return num1 - num2;
}
public static double multiply(double num1, double num2)
{
return num1 * num2;
}
public static double divide(double num1, double num2)
{
return num1 / num2;
}
public static void display(String[] data, double result)
{
if(data[1].equals("/") && data[2].equals("0"))
{
}
else
{
JOptionPane.showMessageDialog(null, data[0] + " " + data[1] + " " + data[2] + " = " + result);
}
}
public static void repeat()
{
int bleh = JOptionPane.showConfirmDialog(null, "More?",null, JOptionPane.YES_NO_OPTION);
if(bleh == JOptionPane.NO_OPTION)
{
flag = false;
JOptionPane.showMessageDialog(null, "Have a good day.");
}
else
flag = true;
}
}