How do I properly use the java.lang.Math? - java

I am in a COMP 110 class which is intro to Java. This specific program is irrelevant to the class but to help my own understanding with Java.
I believe I have imported the tool to allow the program to calculate basic math operations by using "java.lang.Math;"
I understand * is multiplication, / is division, + is addition, - is subtraction, and % finds the remainder.
The final line of the program gives me the error message:
squared.java:14: operator * cannot be applied to java.lang.String,java.lang.String
and I am at a loss for why because I have imported the language Math, which should enable me to use the * to multiply the value variable when I enter "value * value"
import java.util.Scanner;
import java.lang.Math;
public class squared {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
String value = number.nextLine();
System.out.println("The square of the number" + value + "is" + value * value);
}
}

Yes you must first convert it into an Integer, Double, Float, etc in order to do a multiplication on such. So just do
int v = Integer.parseInt(value.trim());
Then
System.out.println("The square of the number"+v+"is"+ (v * v));
Also using operators has nothing to do with Math library. Math library is used like so:
double d = Double.parseDouble(value.trim());
Math.pow(d,2.0); //which does the same thing above

There are two approaches to go about this program -
1) Read the input as String and then convert it to int or
2) Read the input as int(or double?) itself.
Following code shows how you can read the input as int and perform the operation.
Note the code change (value*value) in your sysout statement. When you concatenate any value to a string, it get treated as string, and hence you are getting the error. Put it in parenthesis such that before concatenating, actual value*value operation is performed.
public class squared {
public static void main(String[] args){
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
int value = number.nextInt();
System.out.println("The square of the number"+value+"is"+ (value * value));
}
}
Talking about Math.pow(), it doesn't serve any different purpose here. Using it is same as the way you have done here.

First of all, you don't need to import java.lang.Math. All of the java.lang libraries are already there. Also, you don't need to use the Math library for operations. You use it for things like Math.sin() to find the sine of an angle, or Math.pow() to get the power of one number to another. If you want a full list of the uses for java.lang.Math, here is a link: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
You probably want to store the input in a double, so rather than using number.nextLine(), you may want to use number.nextDouble(), and store it in a double, as below.
double value = number.nextDouble();
You were storing the value as a String, so the computer was reading the input as a quotation, like "cat," rather than the numbers. It doesn't work because what you were trying to do was akin to saying
"cat" * "dog."
Good luck in the class!

Related

Changing Word to Numbers Java

For my current code, I'm creating a word calculator where words are inputted to represent numbers and the calculations are done within the code. The requirements is to input two numbers and an operator into the console. I was able to parse the input into three parts, the first number, the operator, and the second number.
My question is how should I approach when I convert the word into number form? For example, if a user inputted:
seven hundred eighty-eight plus ninety-five
How can I turn that into 788 and 95 so I can do the calculations within the code? My input needs to go up to 1000.
This is part of my code for dividing up the input.
import java.util.Scanner;
public class TextCalc2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
in = in.toLowerCase();
while (!in.equals("quit")) {
if (in.contains("plus")){
String number1 = in.substring(0, in.indexOf("plus") - 1);
String number2 = in.substring(in.indexOf("plus") + 5, in.length());
String operator = in.substring(in.indexOf("plus"),in.indexOf("plus") + 5);
System.out.println(number1);
System.out.println(operator);
System.out.println(number2);
}
}
First of all there are problems in the way you are splitting the input (you have hard coded the operation). I would suggest splitting your input with " " (space) and then analyzing each part of the input separately.
You will have different types of words in your input, one is a single digit number, double digit number, operations and "hundred".
Then you should find which category first word of your input belongs to, if it has "-" it will be double digit, else look into other categories and search for it till you find it. Then based on category decide what you should do with it, if its a single digit, replace it with its equivalent. if its double digit, split and then replace each digit, if its operation store it and cut your input array from there so that you have separated the first value and second one, and if its hundred multiply previous single digit by 100.
After this parsing steps you will have something like this {"700","88"} , {"95"} and plus operation. now its easy to convert each string to its integer value using parse method and then apply the operation.
BTW, it would be easier to use Enum for your constants and just use their ordinal value. Also use the comment that Jared made for your double digit values.
Let me know if you still have question.

Compare first two decimal points

Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.
I tried many things:
1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
2) a = 3.14;
a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001
converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
split uses a regex, so you have to escape the dot.
string.split(".")
should become
string.split("\\.")
With this you should be able to split the string properly and do your comparisons
By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.
You could separate the fractional part for comparison instead
double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see
why you're seeing additional digits after your own numerical operation
your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)
Try this out
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float v1 = 3.13f,v2 = 4.13f;
//Converting float value into String array
String split1[]=Float.toString(v1).split("\\.");
String split2[]=Float.toString(v2).split("\\.");
//Comparing two strings
if(split1[1].equals(split2[1]))
{
System.out.println("Yes");
}
}
}

Formating big numbers in Java

I have an edittext with a maxlength
My question is...
How can I display the value of a bigger number than the maxlenght like the windows calc??
Example:
1.34223423423434e+32
I want this with the edittext maxlength
EDIT: I want this for display and store numbers without having problems with math operations if it's possible
Thanks
This is what the BigInteger class (or BigDecimal, for non-integers) is for.
These classes store numbers with arbitrary precision, and allow for standard arithmetic operations. You can get the exact value of the number as a string, and then format that as you wish (e.g. trimming the length).
(Note that while it may seem like you can use these classes with a NumberFormat instance, this is not recommended as accuracy will be silently lost if the number doesn't fit into a double.)
Here's an example of using it:
// Create a BigDecimal from the input text
final String numStr = editText.getValue(); // or whatever your input is
final BigDecimal inputNum = new BigDecimal(numStr);
// Alternatievly you could pass a double into the BigDecimal constructor,
// though this might already lose precison - e.g. "1.1" cannot be represented
// exactly as a double. So the String constructor is definitely preferred,
// especially if you're using Double.parseDouble somewhere "nearby" as then
// it's a drop-in replacement.
// Do arithmetic with it if needed:
final BigDecimal result = inputNum.multiply(new BigDecimal(2));
// Print it out in standard scientific format
System.out.println(String.format("%e", result));
// Print it out in the format you gave, i.e. scientific with 14dp
System.out.println(String.format("%.14e", result));
// Or do some custom formatting based on the exact string value of the number
final String resultStr = result.toString();
System.out.println("It starts with " + result.subString(0, 3) + "...");
I'm not sure exactly what format you wanted for output, but whatever it is you should be able to manage it with BigDecimals as the backing store.

Regex, excluding non-number

In my program I read input from the console and determine whether it is a number or not. Numbers can be any decimal +-. For instance having 123.18p18 is not allowed since there is a nondigit in there, same with -123.18p18. The bad way of doing this (which I am currently doing) is checking if it is a double and catching exceptions, but since I am just parsing a string I think regex is far better to use here. This is my first day in its use (regex) and it seems like an alien language.
I came up with ".*\\D+.*" but that only handles positive numbers.
Edit: Integers are also acceptable.
You are looking for:
"^[+-]?\\d+([.]\\d+)?$"
Optional plus or minus in the beginning, followed by at least one digit. Before the end of the string there can optionally be one dot followed by at least one digit.
To solve your initial problem, you can use the java.util.Scanner class. It provides methods for testing whether the next input is an integer, double, etc., or even testing whether the next input conforms to a given regular expression.
import java.util.Scanner;
//...
Scanner s = new Scanner(System.in);
while ( s.hasNext() ) {
if ( s.hasNextInt() ) {
int i = s.readInt();
// Some work.
} else if ( s.hasNextDouble() ) {
double d = s.nextDouble();
// Some work.
} else if ( s.hasNext(regex) ) {
String t = s.next(regex);
// Some work.
}
// etc.
}
The following regex might work for you;
It defines a pattern which starts with either a + or - followed by zero or more digits and if there is a decimal point, then it must be followed by at least one digit
"^[+-]?\\d+(?:\\.?\\d+)$"
Try double doubleInstance = Double.parseDouble(string); and proceed...

Convert very small double values to string (with scientific notation) (Java)

I'm trying to print a small double number like 6.67e-11, but using Double.toString() returns 0. What can I do to make it print 6.67e-11 (or something similar) instead?
Unable to reproduce:
public class Test {
public static void main(String args[])
{
double d = 6.67e-11;
System.out.println(Double.toString(d)); // Prints "6.67E-11"
}
}
IIRC, Double.toString() always returns a string which allows the exact value to be round-tripped using Double.parseDouble().
My guess is that you don't actually have a small value - that you have 0, due to some rounding errors in other operations.

Categories