我试图使用扫描仪在JFrame中绘制一个矩形,但是得到以下错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at DrawerAutoRect.main(DrawerAutoRect.java:39)这个程序的目标是选择要绘制的对象的类型,即:线条、矩形、o值,然后输入参数,也就是说,如果它是我正在绘制的矩形,则输入为r, 200,200,400,400,并用于绘制JFrame上具有这些尺寸的矩形。然后,我只需输入" end“,它就会结束,等待输入和绘制对象。
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Scanner;
import javax.swing.JFrame;
public class DrawerAutoRect extends JFrame {
public DrawerAutoRect(){
setSize(1020,1020);
}
public static void paint(Graphics g, int a, int b,int c, int d)
{
Graphics2D g2 = (Graphics2D)g;
g2.drawRect(a, b, c, d);
}
public static void main(String[] args) {
int x1 = 100;
int x2 = 100;
int y1 = 50;
int y2 = 50;
Scanner s = new Scanner(System.in);
String dim = s.next();
while(dim!="end"){
if(dim.equals("r")){
x1 = s.nextInt();
y1 = s.nextInt();
x2 = s.nextInt();
y2 = s.nextInt();
}
}
paint(null, x1, y1, x2, y2);
DrawerAutoRect r = new DrawerAutoRect();
r.setDefaultCloseOperation(EXIT_ON_CLOSE);
r.setVisible(true);
//r.pack();
r.setTitle("Tutorial");
}发布于 2014-08-05 04:44:46
问题是,您的输入不仅包含要查找的标记,而且显然还包含逗号、和空格。
因此,您必须告诉您的Scanner使用特定的分隔符来理解他必须在这个String上使用tokenise您的输入流。
我建议您使用以下正则表达式作为Scanner的分隔符
,\s*|\s+这将使您的输入分为以下几个部分:
请考虑以下示例代码:
try (final Scanner s = new Scanner(System.in)) {
s.useDelimiter(",\\s*|\\s+");
String dim;
do {
dim = s.next();
if (dim.equals("r")) {
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.nextInt());
}
} while (!dim.equals("end"));
}只需输入:
r 1, 2, 3, 4, end..。在控制台上,我得到了以下输出:
1
2
3
4..。它起作用了!
另外,作为附带说明,我想指出,为了比较中的String#equals s,您应该使用String#equals方法,而不是原始比较器。
因此,您应该使用!dim.equals("end")而不是dim != "end" (正如我在示例代码中所做的那样)。
https://stackoverflow.com/questions/25131067
复制相似问题