Java Remove all cases of .0 - java

I want a filter to run through a string and eliminate all of the un-needed .0's from the doubles. I have already tried replaces, but cases like 8.02 turn into 82.
I have a feeling this has been done before, but I cannot find any help.
I am looking for a method that will take in a String, example: "[double] plus [double] is equal to [double]", where the [double] is a double that will need to be checked for the redundant decimal.
Thanks in advance!

let's say you have a string called s that contains text like you described. simply do:
s = s.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");
and you're done.
ok, so i edited this a couple of times. now it works though!

You can do this with a java.text.DecimalFormat object.

Can you not take away the trailing zeros before you construct them into your string? This way you could use the DecimalFormatter method someone posted earlier and then deleted.
NumberFormat formatter = new DecimalFormat("0.##");
String str = formatter.format("8.0200");
System.out.println(str);
Give them credit for the code if they come back.

The other posts assume you're working with a short string containing only decimal.
Assuming you're working with large strings of text, you can use Pattern/Matcher classes (I'm at work, so posting in a hurry. Check for errors)
Use this regex to replace:
/* >1 digits followed by a decimal and >1 zeros. Note capture group on first set of digits. This will only match decimals with trailing 0s, and not 8.0002 */
(\d+)\.0+
Replace with
/* First capture group */
$1
I'm unsure of the regex rules for Java, so use this as a concept to get what you want.

The following program will remove all trailing zeros from the fractional part of a double value. If your requirements are somewhat different, you may need to modify it slightly.
final public class Main
{
public static void main(String...args)
{
System.out.println("Enter how many numbers you want to check:->");
Scanner scan = new Scanner(System.in);
final double KEY_VALUE = 0.0;
final Double TOLERANCE = 0.000000000001d;
int n = scan.nextInt();
double[] a = new double[n];
for (int i = 0; i < n; i++)
{
a[i] = scan.nextDouble();
}
List<Double> newList = new ArrayList<Double>();
for (int k = 0; k < n; k++)
{
if (Math.abs(a[k] - KEY_VALUE) < TOLERANCE)
{
continue;
}
newList.add(a[k]);
}
System.out.println(newList);
}
}
You can specifically use DecimalFormat to truncate the specified number of decimal places, if you need such as follows.
double x=10.4555600500000;
DecimalFormat df=new DecimalFormat("#.##");
System.out.println(df.format(x));
Would return 10.46.

Related

Want to programm calculator, want to change String into real operator

I want to code a simple calculator and already got some code. But now I want to change the String I got there into an Operator. For example:
My input is: "1,5 - 1,1 + 3,2 ="
Now I have a double array and a String array.
So after that I want to put it together, so it calculates this complete task.
double result = double[0] String[0] double[1] ....
I hope you can help there, and I apologize for my grammar etc., english is not my main language.
import java.util.*;
public class calculator
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
double[] zahl;
zahl = new double[10];
double ergebnis;
String[] zeichen;
zeichen = new String[10];
Scanner input = new Scanner (System.in);
while (input.hasNext())
{
if (input.hasNextDouble())
{
zahl[a] = input.nextDouble();
a++;
}
else if (input.hasNext())
{
zeichen[b] = input.next();
if (zeichen.equals ("=")) break;
b++;
}
}
input.close();
}
}
If I type in: "1,5 + 2,3 * 4,2 =" I want to get the result with point before line and without .math
What you want to do is parse a single String and convert it into a mathematical expression, which you then want to resolve and output the result. For that, you need to define a "language" and effectively write an interpreter. This is not trivial, specifically if you want to expand your syntax with bracketing and thelike.
The primary question you have to answer is, whether you want to use a solution (because you are not the first person to attempt this) or if you want to actually write this yourself.
There are "simple" solutions, for example, you could instantiate a javascript engine in Java and input your string, but that would allow much more, and maybe even things you don't want. Or you could use a library which already does this. This Thread already answered a similar question with multiple interesting answers:
How to evaluate a math expression given in string form?
Otherwise, you might be in for a surprise, concerning the amount of work, you are getting yourself into. :)

JAVA truncate scanner input

I have a program that asks the user for an input which is an int(using a scanner).
I only want the program to take in 7 digits.
If the input is not 7 digits I want to truncate it to 7 digits.
So if the number were 12345678 I would want it to be 1234567.
Currently I am storing the input in an array like the following:
for(int i = 0; i > 7; i++)
{
numbers[i] = input1 % 10;
input1 /= 10;
System.out.print(numbers[i]);
//stores the numbers backwards so if input was 123, first element would be 3, 2, 1
}
so that's when I run into the problem if I enter 12345678, it will store it as 8765432. I want it to store as 7654321 instead.
If anyone has any suggestions on my loop making the number store as 1234567 or 7654321, it would be quite helpful :)
An easier way can be to save the input into a String
Then check if length>7, if yes keep the 7 first character, if no, do nothing ;)
String input1 = sc.nextLine();
if(input1.length>7){
input1 = input1.substring(0,7);
}
int input = Integer.valueOf(input1);
It's clearly easier than storing each digit individually or iterate over the input ;)
Edit with '?' ('?' definition and explication)
String input1 = sc.nextLine();
int input = Integer.valueOf(((input1.length>7) ? input1.substring(0,7) : input1);
This allows to not change the value of input1 this will stay the original input
Well, there are several things.
First of all, I think it'd be better for you to use ArrayList and work on Integers, rather than primitive types such as int. If you use ArrayList, then you can simply do .add(Integer e) to put next Integer into your list.
Next thing, your loop should be:
for(int i = 0; i < 7; i++) instead of for(int i = 0; i > 7; i++). See the difference? If you are using i++, then you limit your loop with a <, not >.
As for reversing the input, it's pretty simple, use i-- instead, but I think you can figure this out yourself.
public static void trauncateNumber(int input1) {
String Str=Integer.toString(input1);
//int changeValue=0;
if(Str.length()>7){
//Str=Integer.toString(input1);
Str=Str.substring(0, 7);
input1=Integer.parseInt(Str);
}
//int changeValue=
System.out.println(input1);
}

Parsing fractions

My current goal is to parse fractions and create improper fractions.
For example:
1_1/3 + 5/3
should come into the console as
4/3 + 5/3
Could someone tell me am I going in the right direction and what should I be focusing on?
import java.util.Scanner;
public class FracCalc {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them.");
boolean isTrue = true;
String in = "";
while(isTrue) {
in = input.nextLine();
if (in.equals("quit")) {
System.out.println("Thanks for running FracCalc!");
isTrue = false;
}else{
System.out.println("You asked me to compute" + in);
}
}
}
public static void parse(String in){
int underscore = in.indexOf("_");
int slash = in.lastIndexOf("/");
String wholenumber = in.substring(0, underscore);
String numerator = in.substring(underscore + 1,slash);
String denominator = in.substring(slash + 1);
if (underscore<0 & slash<0) {
in = wholenumber;
} else if (underscore<0 & slash>0) {
in = in;
} else if (underscore>0 & slash>0) {
} else if (underscore>0 & slash<0) {
in = "Error";
}
}
}
I'd say you're definitely on the right track although I'd consider a bit of a different approach to your parsing.
I would parse the string character by character. Iterate through the string and if your current character is a number, append it to a StringBuffer called "currentNumber" or something. If your current character is not a number you need to decide what to do. If it's an underscore, you know that the value in your currentNumber variable is the whole number part. You could then store that in a separate variable and clear your currentNumber buffer. If your current character is a slash character, you'd know that the value in currentNumber is the numerator of your fraction. If the current character is a space character you can probably just ignore it. If it is a '+' or '-', you'll know that what you have in your currentNumber variable is your fraction denominator. You should then also store the symbol in a separate variable as your "operator". There are numerous ways you could implement this. For example you could have logic that said: "if I have a valid value in my numerator and not in my denominator and the character I'm currently looking at is not a valid numeric character, then I have appended all the digits in my denominator to the currentNumber variable and it should therefore now contain my denominator. So put the value in currentNumber into my denominator variable and move on to the next character".
I hope I haven't lost you completely here... but of course this may be a bit too advanced for what you need to do. For example, you didn't specify the format of the input string, will it always be in the exact same format as you mentioned or can it look different? Can the whole number part have two digits or can it be skipped alltogether?
The method I described above is called a finite state machine and if you haven't learnt about them yet your teacher should probably be impressed if you handed in an assignment using this technique. There is a lot of reading material on FSM so Google is your friend.
But just to be clear. Your solution looks like it would work too, it just probably won't be as "dynamic".

Java - Ideas to turn strings into numbers (RegEx/Parsing/etc.)?

I'm reading in from a file, and the input is like this:
Description (1.0,2.0) (2,7.6) (2.1,3.0)
Description2 (4,1)
...
Description_n (4,18) (8, 7.20)
I want to be able to take the numbers inside parentheses and use turn them from strings into numbers so that I can do mathematical operations of them. Right now, to simplify things, my code only reads in the first line and then splits it based on spaces:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("filename.txt")));
//reader reads in the first line
String firstLine = reader.readLine();
//splits into an array of ["Description","(1.0,2.0)","(2,7.6)","(2.1,3.0)"]
String[] parts = first.split(" ");
//now I want to store 1.0, 2, and 2.1 in one array as ints and 2.0, 7.6, and 3.0 in another int array
} catch (Exception e) {
System.exit(0);
}
What are some ways I can store the numbers inside parentheses into two separate arrays of ints (see comment above)? Should I use regular expressions to somehow capture something of the form "( [1-9.] , [1-9.] )" and then pass those into another function that will then separate the first number in the pair from the second and then convert them both into integers? I'm new to regular expression parsing in Java, so I'm not sure how to implement this.
Or is there a simply, better way to do this?
This stores the numbers into Double-arrays (not two-dimensional arrays, arrays of Double objects), since some have .#. int-arrays would eliminate the post decimal part.
It uses the regex \b([\d.]+)\b to find each number within each paren-group, adding each to an ArrayList<Double>. Note that it assumes all input is perfect (nothing like (bogus,3.2). The list is then translated into an array of Double objects.
This should give you a good start towards your goal.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
<P>{#code java DoubleInParenStringsToArrays}</P>
**/
public class DoubleInParenStringsToArrays {
public static final void main(String[] ignored) {
String input = "(1.0,2.0) (2,7.6) (2.1,3.0)";
String[] inputs = input.split(" ");
//"": Dummy string, to reuse matcher
Matcher mtchrGetNums = Pattern.compile("\\b([\\d.]+)\\b").matcher("");
for(String s : inputs) {
ArrayList<Double> doubleList = new ArrayList<Double>();
mtchrGetNums.reset(s);
while(mtchrGetNums.find()) {
//TODO: Crash if it's not a number!
doubleList.add(Double.parseDouble(mtchrGetNums.group(0)));
}
Double[] doubles = doubleList.toArray(new Double[doubleList.size()]);
System.out.println(Arrays.toString(doubles));
}
}
}
Output:
[C:\java_code\]java DoubleInParenStringsToArrays
[1.0, 2.0]
[2.0, 7.6]
[2.1, 3.0]
How to parse per item:
Double.parseDouble("your string here");
As for the storing, I didnt get the pattern you want to store your values. What's the reason why you want 1.0, 2, and 2.1 in 1 array and 2.0, 7.6, and 3.0 to another?
Just do Integer.parseInt(string), or Double.parseDouble(string), then add those to the array. I'm not really 100% sure what you're asking, though.
I would use a String Tokenizer.But need more information and thought for full impl.
This is your line : "Description (1.0,2.0) (2,7.6) (2.1,3.0)"
First thing - can there be cases without parenthesis? Will there always be sets f 2,2,2 numbers ?
Do you want to take care of errors at each number or just skip the line or skip processing if there is an error (like number of numbers does not match?).
Now you need a data structure to hold numbers. You could make a class to hold each individual element in a seperate property if each number has a distinct meaning in the domain or have an array list or simple array if you want to treat them as a simple list of numbers. If a class one sample (incopmplete):
class LineItem{
}
Now to actually break up the string there are many ways to do it. Really depends on the quality of data and how you want to deal with possible errors
One way is find the first opening parenthesis( take rest of string and parse out using a String Tokenizer.
Something like:
int i = str.indexOf("(");
String s2 = str.substring(i);
StringTokenizer st = new StringTokenizer(s2, "() ,";//parenthesis, comma and space
ArrayList<Double> lineVals1 = new ArrayList<Double>();
ArrayList<Double> lineVals1 = new ArrayList<Double>();
int cnt = 0;
while(st.hasMoreTokens()){
cnt++;//use this to keep count of how many numbers you got in line and raise error if need be
String stemp = st.nextToken();
if(isNumeric(stemo)){
if(cnt % 2 == 1){
lineVals1.add(Double.parseDouble(stemp));
}else{
lineVals2.add(Double.parseDouble(stemp));
}
}else{
/raise error if not numberic
}
}
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

Categories

Resources