java - 扫描仪无法扫描

标签 java

我在编写用于生成包含多项选择题和问答题的测试的硬件程序时遇到了问题。一切正常,除了我的程序在阅读论文课的一部分时会跳行。我知道它与扫描仪和 scan.nextline、scan.nextInt 和 scan.next 等有关,但我对如何修复它感到困惑。

感谢您的帮助。

import java.util.*;

public class TestWriter
{
    public static void main (String [] args)
    {
        Scanner scan = new Scanner (System.in);
        String type=null;
        System.out.println ("How many questions are on your test?");
        int num = scan.nextInt ();
        Question [] test = new Question [num];
        for (int i=0; i <num; i++)
        {
            System.out.println ("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
            type = scan.next ();
            scan.nextLine ();
            if (type.equals ("e"))
            {
                test [i] = new Essay ();
                test [i].readQuestion ();
            }
            if (type.equals ("m"))
            {
                test [i] = new MultChoice ();
                test [i].readQuestion ();
            }
        }

        for (int i=0; i <num; i++)
        {
            System.out.println ("Question " + (i+1)+": "+ type);
            test [i].print ();
        }
    }
}

这是作文课

public class Essay extends Question
{
    String question;
    int line;
    public void readQuestion ()
    {
        System.out.println ("How many lines?");
        line = scan.nextInt ();
        scan.next ();
        System.out.println ("Enter the question");
        question = scan.nextLine ();
    }
    public void print ()
    {
        System.out.println (question);
        for (int i=0; i <line; i++)
        System.out.println ("");
    }
}

最佳答案

使用scan.nextInt()会产生如下问题 如果您的输入是“5 5”,nextInt() 将得到下一个整数,留下缓冲区行剩余的“5”。其中剩下的“5”个会被

type = scan.next();

在类测试编写器中:

  System.out.println("How many questions are on your test?");
  int num = scan.nextInt();
  Question[] test = new Question[num];  for(int i=0; i<num; i++)
  {
   System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");

    type = scan.next();

这将产生我上面提到的问题。

要解决这个问题,您可以

a) 确保输入只是一个数字

b) 像这样获取整行 String temp = scan.nextLine(); 然后将其转换为整数。这将使您可以使用字符串并检查它是否是您需要的输入,即第一个字母/数字组是 e/m 还是整数。

scan.nextInt() 的问题在于它只获取输入行的下一个整数。如果输入后有空格,即“5 5”,它将仅获取下一个 int 5 并留下“5”。

因此我建议使用 scan.nextLine() 并操纵字符串以确保可以处理和验证输入,同时确保您不会对扫描仪的位置感到困惑。

如果你正在处理一个带有各种参数的输入,你应该使用 .next()/.nextInt() 来特别捕获,例如“25 男学生 1234”,在这种情况下,代码将是这样的

int age = scan.nextInt(); 
String sex = scan.next(); 
String job = scan.next(); 
int score = scan.nextInt();

关于java - 扫描仪无法扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323338/

相关文章:

Java - 编程双向控制台窗口

java - 将 PhantomJS 二进制文件添加到 Maven 项目的更好方法?

java - Netbeans 中的 CopyLibs 是什么?

java - RecyclerView和CardView实现onClick

java - Google App Engine/Java SDK 在哪里存储记录和 blob?

java - 如何在 windows-64bit 中设置 java 路径和类路径

java - 获取ArrayList值?

java - Install4j 可配置表单文本字段从验证表达式重置

java - Spring : how to apply role to existing JWT token

java - 将数组分解为子数组