Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

SnowLeopard2008

macrumors 604
Original poster
Jul 4, 2008
6,772
18
Silicon Valley
I have two JTextFields. One has "1909 mAh" in it, and the other has "2696 mAh" in it. I need to figure out a way to grab the numbers only (1909 and 2696), and divide them. I then need to multiply that by 100 to get a percentage. I want to display this number in another JTextField and add the "%" sign at the end. How would I accomplish this? I've been trying for almost an hour!

Thanks in advance,
Snow Leopard
 

MrSIXW

macrumors newbie
Jan 15, 2009
3
0
With what you have, I would do would be the following

  1. use the getString function on each text box
  2. Tokenize the strings obtained from the text boxes using StringTokenizer
  3. Attempt to convert each token a number, Integer.parseInt() etc should should help you
  4. When you have both numbers, do the devide and multiply
  5. Set text in the third textbox to the number and concat on the %, so Integer.toString().concat("%")

All that said, you would be better off validating the input on each text box to limit it to only number entry. I'd look into JFormattedTextFields if I were you as alot of the issues go away doing this.
 

jeremy.king

macrumors 603
Jul 23, 2002
5,479
1
Holly Springs, NC
Without any exception handling, and making a STRONG assumption on that exact format you provided. No validation here either.

Code:
String first = firstTextField.getText();
String second = secondTextField.getText();
Float theValue = Float.parseFloat(first.replace(" mAh", "")) / Float.parseFloat(second.replace(" mAh", "")) * 100;
thirdTextField.setText(theValue + "%");

This better not be homework!
 

SnowLeopard2008

macrumors 604
Original poster
Jul 4, 2008
6,772
18
Silicon Valley
Without any exception handling, and making a STRONG assumption on that exact format you provided. No validation here either.

Code:
String first = firstTextField.getText();
String second = secondTextField.getText();
Float theValue = Float.parseFloat(first.replace(" mAh", "")) / Float.parseFloat(second.replace(" mAh", "")) * 100;
thirdTextField.setText(theValue + "%");

This better not be homework!

Thanks! No, it's not homework. My Java class ended over a month ago. I'm developing this Java app for my dad's work. It's not going to be sold for money or etc. I'm going to add that in and post back results!
 

SnowLeopard2008

macrumors 604
Original poster
Jul 4, 2008
6,772
18
Silicon Valley
it complains about a class being expected. I put in this in the beginning:

Code:
import java.util.StringTokenizer;

Is that right? Below is a screenshot of terminal's error when compiling.
 

Attachments

  • Picture 1.png
    Picture 1.png
    70.2 KB · Views: 111

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
it complains about a class being expected. I put in this in the beginning:

Code:
import java.util.StringTokenizer;

Is that right? Below is a screenshot of terminal's error when compiling.

float is a primitive, Float is its wrapper class. You are trying to call methods on the primitive. Just swap it.

-Lee
 

SilentPanda

Moderator emeritus
Oct 8, 2002
9,992
31
The Bamboo Forest
Hasn't StringTokenizer been depreciated? I was thinking String.split() was all the rage now.

I guess not technically depreciated but in the 1.4.2 docs and up Stringtokenizer says this:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

StringTokenizer certainly works though. And I guess if you're using 1.3 it's all you have.

Also does the user type in mAh? Will it always be mAh? If so you might consider putting that as a label outside the text box. Then you don't have to take the numeric part since it should all be numeric (which you could validate against a regex).
 

MrSIXW

macrumors newbie
Jan 15, 2009
3
0
Hasn't StringTokenizer been depreciated? I was thinking String.split() was all the rage now.

I guess not technically depreciated but in the 1.4.2 docs and up Stringtokenizer says this:



StringTokenizer certainly works though. And I guess if you're using 1.3 it's all you have.

Also does the user type in mAh? Will it always be mAh? If so you might consider putting that as a label outside the text box. Then you don't have to take the numeric part since it should all be numeric (which you could validate against a regex).

Ah yes, it is. Appologies I have been using StringTokenizer since, well, forever (well before 1.4) and so fell into the trap of just using it and using it. Didnt know that it had been depracated as I never refer to the API page for it, but thannks for the heads up.

Sorry OP, you should have used String.split() and not get in the habit of using StringTokenizer.
 

jeremy.king

macrumors 603
Jul 23, 2002
5,479
1
Holly Springs, NC
Try replaceAll() instead. replace() only supports char and CharSequence. Sorry about that.

See Javadoc for more information.

You can make it smarter by stripping out any non-digit character
Code:
full.replaceAll("\\D", "");
 

SnowLeopard2008

macrumors 604
Original poster
Jul 4, 2008
6,772
18
Silicon Valley
Thanks everyone for your help! The "replaceAll" method worked. Before, it would compile correctly, but not display the numbers in the JTextField. I was trying to make a simple battery gauge app that gets its information from a .txt file (this is on Linux) and display it through my app. And the current capacity of the battery (percentage). Next, I'm trying to have it update itself on intervals of 2 seconds but also need advice on how to do that.

I'm relatively new to Java, I took a beginner course and completed it just a few weeks ago.


One last thing, how do you round numbers in Java? I just want 2 decimal points, not like 5.
 

SnowLeopard2008

macrumors 604
Original poster
Jul 4, 2008
6,772
18
Silicon Valley
To wait a certain amount of time, you can use Thread.sleep(). It takes a value in ms. Note that, as with all sleeps, you are only guaranteed that execution paused for at least the time given, not exactly the time given.

As for formatting numbers, look into DecimalFormat:
http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html

-Lee

Thanks! The time issue is moot. As long as it updates every few seconds and not have me click the update button, then it's all in good hands.

Note to self: Must learn more Java. :D

EDIT: I need something that will loop the entire process to display the data to the JTextFields, and also have a delay period. Like the app will wait for 2 seconds, grab the data, display it, etc and wait again and update the JTextFields with new data, etc. Over and over and over. I tried putting a for loop and the Thread.sleep() inside it; but it appears to not work. Any ideas?
 

4409723

Suspended
Jun 22, 2001
2,221
0
Here's an example to get two digits of precision to your numbers, although I doubt this is the best way, it does work.

Code:
import java.text.NumberFormat;

public class Example {

	private static final int PRECISION = 2;

	public static void main(String[] args) {
		double f1 = 1.0;
		double f2 = 1.00;
		double f3 = 1.001;
		double f4 = 1.12482382;
		double f5 = 1.12512382;

		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(PRECISION);
		nf.setMinimumFractionDigits(PRECISION);

		System.out.println(nf.format(f1));
		System.out.println(nf.format(f2));
		System.out.println(nf.format(f3));
		System.out.println(nf.format(f4));
		System.out.println(nf.format(f5));
	}
}


When I run it I get this output:

Code:
 wlb$ java Example
1.00
1.00
1.00
1.12
1.13

I miss coding in Java at work...
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.