It looks like you're using .getText() so I'm assuming your working with a GUI. How about this using JavaFX?
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.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class StringToIntTextField extends Application {
@Override
public void start(Stage primaryStage) {
TextField tf = new TextField();
Button btn = new Button();
btn.setPrefWidth(150);
btn.setText("Convert to Int'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
int n = Integer.parseInt(tf.getText());
System.out.println(n + 1);
}
});
GridPane gp = new GridPane();
gp.add(btn, 0, 1);
gp.add(tf, 0, 0);
Scene scene = new Scene(gp, 150, 75);
primaryStage.setTitle("String -> Int");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This will only work if an actual integer is typed. If it is empty or a word/mixed data it will crash. You'll want to use a try/catch for InputMismatch Exception to fix this.