2012-12-04 38 views
1

我正在寫一個簡單的數學問題的程序。我試圖做的是讓它即使我輸入一個字符串到掃描儀級別,它不會給我一個錯誤。水平是選擇數學難題的難點。我試過parseInt,但現在不知所措。我該怎麼做,以便當我輸入一個值到掃描儀,如果它不是一個整數它不會給我一個錯誤?

import java.util.Random; 
import java.util.Scanner; 
public class Test { 
    static Scanner keyboard = new Scanner(System.in); 
    static Random generator = new Random(); 
    public static void main(String[] args) { 
     String level = intro();//This method intorduces the program, 
     questions(level);//This does the actual computation. 
    } 
    public static String intro() { 

     System.out.println("HI - I am your friendly arithmetic tutor."); 
     System.out.print("What is your name? "); 
     String name = keyboard.nextLine(); 
     System.out.print("What level do you choose? "); 
     String level = keyboard.nextLine(); 
     System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + "."); 
     System.out.println("Good luck."); 
     return level; 
    } 
    public static void questions(String level) { 
     int value = 0, random1 = 0, random2 = 0; 
     int r = 0, score = 0; 
     int x = Integer.parseInt("level"); 
     if (x==1) { 
      r = 4;   
     }  
     else if(x==2) { 
      r = 9; 
     } 
     else if(x==3) { 
      r = 50; 
     } 
     for (int i = 0; i<10; i++) { 
      random1 = generator.nextInt(r);//first random number. 
      random2 = generator.nextInt(r);//second random number. 
      System.out.print(random1 + " + " + random2 + " = "); 
      int ans = keyboard.nextInt(); 
      if((random1 + random2)== ans) { 
       System.out.println("Your answer is correct!"); 
       score+=1; 
      } 
      else if ((random1 + random2)!= ans) { 
      System.out.println("Your answer is wrong!"); 
      } 
     } 
     if (score==10 || score==9) { 
      if (score==10 && x == 3) { 
       System.out.println("This system is of no further use."); 
      } 
      else { 
       System.out.println("Choose a higher difficulty"); 
      } 
      System.out.println("You got " + score + " out or 10"); 
     } 
     else if (score<=8 && score>=6) { 
      System.out.println("You got " + score + " out or 10"); 
      System.out.println("Do the test again"); 
     } 
     else if (score>6) { 
      System.out.println("You got " + score + " out or 10"); 
      System.out.println("Come back for extra lessons"); 
     } 
    } 
} 

回答

0

我看到的第一個錯誤是,你試圖Integer.parseInt()一個字符串 「水平」,而不是字符串變量指定的水平,

int x = Integer.parseInt("level"); 

應該

int x = Integer.parseInt(level); 

此外,在定義級別時,您可以使用keyboard.nextInt而不是keyboard.nextLine

String level = keyboard.nextInt(); 

然後,你就不必在

Integer.parseInt()操作後做
相關問題