【发布时间】:2017-01-07 08:14:44
【问题描述】:
我要从用户那里得到一个整数半径,然后显示圆的面积和周长。如果用户输入负整数或整数以外的其他值(a 或 5.6),它会要求用户重新输入。
下面是捕获错误输入的代码,但它使用的是 Scanner,我需要使用 JOptionPane。
import java.util.Scanner;
public class GetCircle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius = 0;
System.out.print("Please enter size of radius (Must be integer): ");
while (true){
if(input.hasNextInt()){
radius = input.nextInt();
if (radius < 0){
System.out.println("That is not a valid number, please try again :");
} else {
System.out.println("The radius is: " + radius);
}
} else {
System.out.println("That is not a valid number, please try again :");
input.next();
}
}
}
}
我不知道如何将 hasNextInt 与 JOptionPane 一起使用....有人可以帮忙吗?
这是我现在拥有的 JOptionPane:
import javax.swing.JOptionPane;
public class Radius
{
public static void main(String[] args)
{
String radius = JOptionPane.showInputDialog(null,"Enter
Radius","Radius",JOptionPane.QUESTION_MESSAGE);
Integer.parseInt(radius);
JOptionPane.showMessageDialog(null,"the string you entered is: " + radius, "results",JOptionPane.PLAIN_MESSAGE);
}
}
【问题讨论】:
-
您的问题有点不清楚,JPanel 和 hasNextInt 之间的关系是什么,以及,您到底想做什么?
-
当我使用 JPanel 时,我不知道如何像使用扫描仪和 hasext.Input 那样只接受正整数
-
你的意思是
JOptionPane而不是 JPanel 对吧? -
是的,谢谢,我对问题进行了更改......我很抱歉。如您所知,我是初学者
-
如果你明白你需要这样的东西? alvinalexander.com/sites/default/files/users/user3/…
标签: java java.util.scanner joptionpane