日期:2014-05-20  浏览次数:20693 次

以下程序运行完之后想再继续做题需要再运行。如何做到重复出题,按某一健才不出题那
import java.util.Random;
import java.util.Scanner;
public class JiaFa 
{
int a;
  int b;
  int sum;
  public int JiaF()
   
  {
  Random random = new Random();
  this.a = random.nextInt(10);
  this.b = random.nextInt(10);
  System.out.println(a + "+" + b+ "=");
  return sum = a + b;
 
}
  public void showTitle()
  {
  System.out.println("请计算此题目:");
  }

public static void main(String[] args) 
{  
JiaFa he = new JiaFa();
 
he.showTitle();
he.JiaF();
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();

if( he.sum == c)
{
System.out.println("正确。");
}
else
{
System.out.println("错误,正确答案为: " + he.sum );
}

  }
}


------解决方案--------------------
输入q后按回车退出
Java code

    public static void main(String[] args) {
        JiaFa he = new JiaFa();
        Scanner sc = new Scanner(System.in);

        while (true) {
            he.showTitle();
            he.JiaF();
            int c;
            try {
                c = sc.nextInt();
                if (he.sum == c) {
                    System.out.println("正确。");
                } else {
                    System.out.println("错误,正确答案为: " + he.sum);
                }
            } catch (InputMismatchException e) {
                String s = sc.nextLine();
                if (s.equals("q"))
                    break;
            }
        }
    }