简体   繁体   中英

How do i convert a variable string to an integer

I have tried the other solutions available online but none of them work for me for some reason. The conversion to the string is working but then when i try converting that string to an integer it does not work

String cs = (janout.getText().to string()); Integer yo = Integer.valueOf(cs);

Janout is a Text View getting it's value from a text input

This code isn't working for some reason, I think it has something to do with the string being a variable

    public class StringToInt {

    public static void main(String[] args) {
        
        String sNumber = "12";
        int iNumber = Integer.parseInt(sNumber);
        
        // Perform addition to prove it worked
        System.out.println(iNumber + 1);
 
    }
    
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM