Domanda

Sto cercando di fare un JOptionPane ottenere un ingresso e assegnarlo a un int, ma io sono sempre alcuni problemi con i tipi di variabili.

sto cercando qualcosa di simile:

Int ans = (Integer) JOptionPane.showInputDialog(frame,
            "Text",
            JOptionPane.INFORMATION_MESSAGE,
            null,
            null,
            "[sample text to help input]");

Ma io sono sempre:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot
be cast to java.lang.Integer

Il che suona logica ancora, non riesco a pensare ad un altro modo per fare questo accadere.

Grazie in anticipo

È stato utile?

Soluzione

È sufficiente utilizzare:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

Non si può lanciare un String a un int, ma è possibile convertire usando Integer.parseInt(string).

Altri suggerimenti

Questo perché l'ingresso che l'utente inserisce nel JOptionPane è un String e questo viene memorizzato e restituiti come String.

Java non è possibile convertire tra corde e il numero di per sé, è necessario utilizzare specifiche funzioni, basta usare:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Si noti che Integer.parseInt genera NumberFormatException se la stringa passata non contiene una stringa analizzabile.

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}
String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Ora il vostro Int_firstnumber contiene valore intero di String_fristNumber.

Speranza ha aiutato

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top