How to divide two numbers without using the "/" symbol? - java

I wrote some code pertaining to the problem but I just can't get it to work. After I input the two numbers, the program gets stuck in an infinite loop. Is there any way this method could work or is it outright wrong?
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the numerator and denominator respectively : ");
double a = input.nextDouble();
double b = input.nextDouble();
double c;
for(c=0;;c+=0.000000000001){
if(b*c==a){
break;
}
}
System.out.print(c);
}
}

I can think of one way without a slash:
double c = a * Math.pow(b, -1);
You can also substitute a Unicode escape for the / character.
double c2 = a \u002f b;
You can also convert to BigDecimals, use the divide method, and then convert the quotient back to a double.
double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue();

You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b
public class HelloWorld{
public static void main(String []args){
System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b)));
}
}
You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself.
For example if b = 0
Throw error
if a<0 and b>0
System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b)));
etc.

System.out.println("The result is : " + (a * Math.pow(b, -1)));

public class Num {
public static void main(String[] args) {
double num, den, res;
num = 10;
den = 2;
res = Math.pow(Math.E, (Math.log(num)-Math.log(den)));
System.out.println(res);
}
}

Related

Reverse a three digit int; if there is a leading zero in the output it shoud be left out

First of all, a similar queston has already been asked here: How to calculates the number by reversing its digits, and outputs a new number
I am at the beginning of the Java trail at [Jetbrains/hyperskill][1] and the accepted
[1]: https://hyperskill.org/learn/step/2217
answer to the above question is not yet taught at Jetbrains, that's why asking this question.
Here is what I have:
import java.util.Scanner;
public class Main3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your number: ");
int a = scanner.nextInt();
int hundreds = (a % 1000) / 100;
int tens = (a % 100) / 10;
int ones = a % 10;
System.out.println(ones + "" + tens + "" + hundreds);
}
}
To be clear, if the input is 320 for instance, the output should be 23, not 023.
Just to clarify, the only subjects taught at this level is Types and variables, Naming variables, Arithmic operations, Increment and decrement, Strings, Basic literals, Printing data, Scanning the input.
you can convert the hundreds tens and ones into a integer. and print this one.
int number = 100*hundreds + 10*tens + ones;
System.out.println(number);
I saw the problem and the below solution should be good to handle the cases you mentioned
public static void reverse(int num) {
int rev=0;
while(num>0) {
int rem = num%10;
rev=rev*10+rem;
num/=10;
}
System.out.println(rev);
}
How about getting benefit from StringBuilder?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
StringBuilder stringBuilder = new StringBuilder(String.valueOf(scanner.nextInt())).reverse();
if (stringBuilder.charAt(0) == '0') {
stringBuilder.deleteCharAt(0);
}
System.out.println(stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
var n = scanner.nextInt();
System.out.print(n / 100 + 10 * (n / 10 % 10) + 100 * (n % 10));
}
}
Credit for this answer goes to #OlgaAI

Comparing a double to Math.PI (converting double to String)

I'm trying to write a program that compares a double (entered by the user) to the constant Math.PI, after having converted both values to Strings and then comparing them char by char. I'm getting errors but I'm not able to see where I should change my code. Any tips/help is greatly appreciated!
import java.util.Scanner;
public class Main {
private static int matches = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter value to compare");
double compare = scan.nextDouble();
compare(compare);
}
public static int compare(double value){
String input = String.valueOf(value);
String original = String.valueOf(3.523);
//String.valueOf(Math.PI);
if(input.charAt(0) == 3){
for(int i = 3; i <= input.length(); i++){
if(input.charAt(i) == (original.charAt(i))){
matches++;
}
}
return matches;
} else
return matches;
}
}
Your question is not clear
What is concretely the expected behavior here?
I can't manage to understand your thought process in the compare method.
If you wan't to compare a double with Math.PI, it is easy as double are primitive variables, you can use the "==" operator, just do:
if (scannedValue == Math.PI)
System.out.println ("values are equals");
And for the runtime exception that you have it is because you did not pass a correct double variable to your scanner.
https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html

Java: Calling variables of user input from one method to another

I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}
To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}

How to make main method calculate return value?

I wanted the user to enter the pay rate and hours worked. If the hours are 40 or below, it is to multiply the pay rate and the hours together. All of that is to happen in one method and the main method is supposed to call this. However, my program does nothing with the values.
package homework6;
import java.util.Scanner;
public class Homework6 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double T1 = getTotalPay(r, h);
}
public static double getTotalPay(double r, int h){
/*If the number of hours is less than or equal to 40, it simply
multiplies them together and returns the result.*/
if (h <= 40) {
return r*h;
}
}
}
Most likely, you simply need to print the returned value:
...
double T1 = getTotalPay(r, h);
System.out.println("Total pay: " + T1);
As a matter of style, Java variables should start with a lower letter. You should change the name T1 to t1 (or, better, to something like totalPay that is more comprehensible).
Just to clarify: the above goes inside your main() method.
If you want to be fancy, you can format the result as currency:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double totalPay = getTotalPay(r, h);
System.out.println("Total pay: " +
NumberFormat.getCurrencyInstance().format(totalPay)
);
}
First of all, you need to print this returned value:
System.out.println(T1);
Second of all, your getTotalPay(double r, int h) method must always return something or throw an exception if the return type declared is not void. Right now it only returns something when the condition is satisfied. Did you even get this to compile? This method should look something like this:
public static double getTotalPay(double r, int h){
if (h <= 40){
return r*h;
} else {
return 0;
}
}

Java fraction calculator

I'm really new to Java programming and I have an assignment due for my AP Computer Programming class, so bear with me. I have to figure out how to multiply two fractions together. I was wondering if there was any way to declare a variable inside a method and use it outside that method (my while loop in the intro method). Thank you, hope that wasn't confusing!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
This short answer is "no". Others have already explained why... but here's two possible alternatives. I don't know if you've learned these concepts yet, but the first alternative has to do with passing by reference vs. passing by value, and the second alternative has to do with object-oriented programming.
Alternative #1:
You can declare a variable outside a method, pass it to the method and use it, and then the variable is available outside the method because it was declared outside the method. I think an example will help make this more clear:
void foo () {
Integer a = 1;
Integer b = 2;
bar(a,b);
System.out.println("a = " + a + ", b = " + b);
}
void bar (Integer a, Integer b) {
a = 4;
b = 8;
}
And the result should be a = 4, b = 8. However, it's very important to note that this works because Integer (unlike int) is a class so its objects are passed by reference. If a and b were just ints, then they would be passed by value. That means that bar() would have it's own copy of a and b separate from foo()'s, and modifications to the variables within bar() would not affect foo()'s copies. For example:
void foo () {
int a = 1;
int b = 2;
bar(a,b);
System.out.println("a = " + a + ", b = " + b);
}
void bar (int a, int b) {
a = 4;
b = 8;
}
This would produce the result a = 1, b = 2.
I don't really like this method because it's pretty ugly and easy to make a mistake, but it is possible and will work if done correctly. Plus if you're not doing object-oriented code, your choices may be this or just don't use a function for that part (which is not usually good design). Although this kind of thing is much more common in languages like C and C++. But those languages are more explicit about pass by value or reference, and you have to manipulate pointers manually (whereas Java hides its pointers from the programmer), so it's harder to get confused about when something will be passed by value or reference (though easier to make other kinds of mistakes).
Alternative #2:
This would be my preference, given the choice, but only if you've learned some about object-oriented programming. If you haven't learned that yet, I'd go with another approach (but feel free to read on if you're curious).
I would create a fraction class that has member variables for the numerator and denomonator (and whole number part if you're required to support that - although personally I'd reduce fractions with whole number parts to just numerator and denomonator anyhow, because that's how I do math). Then I'd make a constructor that takes a String parameter, and the body of that constructor would work much like your parse() method. So that would let you do something like this...
String strFractionString = /* initialize the string, e.g., reading from input */
Fraction myFrac = new Fraction(strFractionString); // parses string and assigns num & denom
System.out.println("My Fraction: " + myFrac.numerator + "/" + myFrac.denominator);
Nope, the scope of the variable will be limited to the method you created it in.
You'll have to declare the variable outside of that method, if you want to use it outside that method.
Here's a helpful resource on variable scope.
Assuming that you want the function parse() to return both a numerator and a denominator, there are several ways to accomplish this.
The OO way is to define a class that has two fields, a numerator and a denominator, and have parse() return an instance of this type
class Fraction {
public int Numerator = 0;
public int Denominator = 1;
public Fraction(int numerator, int denominator) {
Numerator = numerator;
Denominator = denominator;
}
public static Fraction parse(String fractionString) {
int num, denom;
// Your parse code (without the int num and int denom declarations) goes here.
return new Fraction(num, denom);
}
}
Your calling code would look like this:
Fraction f1, f2;
f1= Fraction.parse(fraction1);
f2= Fraction.parse(fraction2);
int num = f1.Numerator * f2.Numerator;
int denom = f1.Denominator * f2.Denominator;
Variables declared inside a method are encapsulated as local variables and can't be used outside the method.
If you wanted to use say the String frac do this
public class javatest3 {
static String frac;
public static void main(String[] args){
// now you can use frac here
}
public static void parse(String fraction) {
if (fraction.contains("_")){
...
frac = mixed.nextToken();
}
}
}
Just declare the variable outside of any methods. Make sure and make the variable static. Then just initialize in the method. That way it can be used in any of the methods inside that class. Here's an example of how you'd do that.
package testPackage;
public class Test {
public static int waffle = 5;
public static void main(String[] args) {
method1();
method2();
}
public static void method1() {
System.out.println("Heyy Everyone");
System.out.println("Waffle is " + waffle); // Print waffle before change
waffle = waffle + 12 - 4; // Change waffle;
System.out.println("Method 1 set waffle to " + waffle); // Print waffle after change after
} // change in method2
public static void method2() {
System.out.println("Waffle is " + waffle); // Print waffle in method2 after method1's change
waffle = waffle * 3; // Change waffle
System.out.println("Waffle is now set to " + waffle);// Print waffle/ after change in method2
}
}
Your original code prints and separates the fractions and operands. The assignment we have right now in AP CS requires us to separate the fractions into a numerator, operand, and demoninator. It would look something like this.
StringTokenizer st= new StringTokenizer (input);
And then use your find(); method to call each part in
Here is my code to multiply the fraction. More simpl, hopefully will answer your question.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3
{
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args)
{
javatest3 javatest3 = new javatest3();
System.out.println("Enter an expression (or \"quit\"): "); // prompts
// user for
// input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] array = null;
try {
array = in.readLine().trim().split(" ");
/*
* I get the array[0] and array[2], it because 2/3 * 3/4
* 2/3 is array[0], * is array[1] and 3/4 is array[2]
*/
String[] arrayX = array[0].split("/");
String[] arrayY = array[2].split("/");
String result = javatest3.multiplyFaction(
Integer.valueOf(arrayX[0]), Integer.valueOf(arrayY[0]),
Integer.valueOf(arrayX[1]), Integer.valueOf(arrayY[1]));
System.out.println("Result: " + result);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// intro();
}
private String multiplyFaction(int x1, int y1, int x2, int y2)
{
int mf1 = x1 * y1;
int mf2 = x2 * y2;
return String.valueOf(mf1) + "/" + String.valueOf(mf2);
}
// public static void intro()
// {
// Scanner input = new Scanner(System.in);
// String user = input.nextLine();
// while (!user.equals("quit") & input.hasNextLine()) { // processes code
// // when user
// // input does
// // not equal
// // quit
// StringTokenizer chunks = new StringTokenizer(user, " "); // parses
// // by
// // white
// // space
// String fraction1 = chunks.nextToken(); // first fraction
// String operand = chunks.nextToken(); // operator
// String fraction2 = chunks.nextToken(); // second fraction
// System.out.println("Fraction 1: " + fraction1);
// System.out.println("Operation: " + operand);
// System.out.println("Fraction 2: " + fraction2);
// System.out.println("Enter an expression (or \"quit\"): "); // prompts
// // user
// // for
// // more
// // input
//
// while (user.contains("*")) {
// parse(fraction1);
// parse(fraction2);
// System.out.println("hi");
// int num = num1 * num2;
// int denom = denom1 * denom2;
// System.out.println(num + "/" + denom);
// user = input.next();
//
// }
//
// }
// }
// public static void parse(String fraction)
// {
// if (fraction.contains("_")) {
// StringTokenizer mixed = new StringTokenizer(fraction, "_");
// int wholeNumber = Integer.parseInt(mixed.nextToken());
// System.out.println(wholeNumber);
// String frac = mixed.nextToken();
// System.out.println(frac);
// StringTokenizer parseFraction = new StringTokenizer(frac, "/"); // parses
// // by
// // forward
// // slash
// int num = Integer.parseInt(parseFraction.nextToken());
// System.out.println(num);
// int denom = Integer.parseInt(parseFraction.nextToken());
// System.out.println(denom);
//
// }
// else if (!fraction.contains("_") && fraction.contains("/")) {
// StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); // parses
// // by
// // forward
// // slash
// int num = Integer.parseInt(parseFraction.nextToken());
// System.out.println(num);
// int denom = Integer.parseInt(parseFraction.nextToken());
// System.out.println(denom);
//
// }
// else {
// StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
// int num = Integer.parseInt(whiteSpace.nextToken());
// System.out.println(num);
// }
// }
}

Categories