Example to get number, int or float, from part of a string.
|
Get number (int, float) from part of a string |
package javafx_convertnumber;
import java.util.Scanner;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_convertNumber extends Application {
@Override
public void start(Stage primaryStage) {
final TextField fieldInput = new TextField();
final Label labelOrg = new Label();
final Label labelReplaced = new Label();
final Label labelInt = new Label();
final Label labelLastInt = new Label();
final Label labelLastFloat = new Label();
Button btn = new Button();
btn.setText("Convert");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String org = fieldInput.getText();
String replaced = org.replaceAll("[^0123456789.]", " ");
labelOrg.setText(org);
labelReplaced.setText("replaced: " + replaced);
labelInt.setText("int: " + parseToInt(replaced));
labelLastInt.setText("Last int: " + parseLastInt(replaced));
labelLastFloat.setText("Last float: " + parseLastFloat(replaced));
}
});
VBox vBox = new VBox();
vBox.getChildren().addAll(fieldInput, labelOrg, labelReplaced,
labelInt, labelLastInt, labelLastFloat, btn);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private int parseToInt(String in){
int result = 0;
try{
result = Integer.parseInt(in);
}catch(NumberFormatException ex){
}
return result;
}
//get last int
private int parseLastInt(String in){
int result = 0;
Scanner scanner = new Scanner(in);
while(scanner.hasNext()){
if(scanner.hasNextInt()){
result = scanner.nextInt();
}else{
scanner.next(); //ignore
}
}
return result;
}
//get last float
private float parseLastFloat(String in){
float result = (float)0.0;
Scanner scanner = new Scanner(in);
while(scanner.hasNext()){
if(scanner.hasNextFloat()){
result = scanner.nextFloat();
}else{
scanner.next(); //ignore
}
}
return result;
}
}
No comments:
Post a Comment