特殊字符使我的程序崩溃?

时间:2014-11-10 23:53:44

标签: java oop variables

在我的程序中,我有2种模式。一个用于测验插入,另一个用于测验解决方案。每当我在我的字符串输入(ShortAnswerQuestion或FillInTheBlank)中使用特殊字符甚至空格时,我都会遇到运行时错误,或者我的程序将来会走2到3步。没有空格/特殊字符,完美无缺。我能解决这个问题吗?这是我的主要内容:

公共类QuizApplication {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Scanner s=new Scanner(System.in);
    int n,m,l;
    System.out.println("This is the insertion mode\n");
    System.out.println("How many short-answer questions would you like to include in your quiz?");
    n=s.nextInt();
    ShortAnswerQuestion[] qu0= new ShortAnswerQuestion[n];
    int i;
    for(i=0;i<n;i++){
        System.out.println("Please insert question "+(i+1)+": ");
        String Q0=s.next();
        System.out.println("Please insert the correct answer: ");
        String A0=s.next();
        qu0[i]=new ShortAnswerQuestion(Q0,A0);


    }
    System.out.println("How many fillin the blank questions would you like to include in your quiz?");
    m=s.nextInt();
    FillInBlankQuestion[] qu1= new FillInBlankQuestion[m];
    int o;
    for(o=0;o<m;o++){
        System.out.println("Please insert question "+(o+1)+": ");
        String Q1=s.next();
        System.out.println("Please insert the correct answer: ");
        String A1=s.next();
        qu1[o]=new FillInBlankQuestion(Q1,A1);
    }
    System.out.println("How many true or false questions would you like to include in your quiz?");
    l=s.nextInt();
    TrueFalseQuestion[] qu2= new TrueFalseQuestion[l];
    int x;
    for(x=0;x<l;x++){
        System.out.println("Please insert question "+(x+1)+": ");
        String Q2=s.next();
        System.out.println("Please insert the correct answer: ");
        boolean A2=s.nextBoolean();
        qu2[x]=new TrueFalseQuestion(Q2,A2);


}
    System.out.println("Moving to Quiz Mode\n");
    System.out.println("Short-answer questions:\n");
    for(i=0;i<n;i++){
        System.out.println("Question "+(i+1)+" \n"+qu0[i].getMyText());

        System.out.println(qu0[i].CheckAnswer(qu0[i].GetAnswer()));
            } 
    System.out.println("\nFill-in the blank questions:\n");
    for(o=0;o<m;o++){
        System.out.println("Question "+(o+1)+" \n"+qu1[o].getMyText());

        System.out.println(qu1[o].CheckAnswer(qu1[o].GetAnswer()));
            }
    System.out.println("\nTrue or False questions:\n");
    for(x=0;x<l;x++){
        System.out.println("Question "+(x+1)+" \n"+qu2[x].getMyText());

        System.out.println(qu2[x].CheckAnswer(qu2[x].GetAnswer()));
            }
    System.out.println("END OF QUIZ");

}}

1 个答案:

答案 0 :(得分:3)

您正在使用s.next(),其中只读取一个单词,您应该使用s.nextLine()来读取整行。

要解决此问题,您需要更改每个

s.next()

s.nextLine()

但是,在您致电s.nextLine()s.nextInt()后,您还需要额外添加s.nextBoolean()。原因是s.nextInt()s.nextBoolean()不会读取它们读取的值后面的行尾字符。所以你写的地方

l=s.nextInt();

你真的想要

l=s.nextInt();
s.nextLine();

最后,使用单字母变量名称是一个非常糟糕的主意。它使您的代码更难以阅读和理解。最好使用变量名来说明每个变量的用途。