简体   繁体   English

为什么我的代码不起作用?

[英]Why doesnt my code work?

This method is supposed to load the next question into a GUI. 该方法应该将下一个问题加载到GUI中。

public void readNextEntry() {

    list = new ArrayList<String>();

    scanner = new Scanner(linesFromFile.get(currentQuestion)).useDelimiter(",|\n");
    for (int i = 0; i < 8; i++) {
        list.add(scanner.next());
    }
}

The text file it is supposed to load from is as follows in the format: 它应该从中加载的文本文件如下格式:

001,what color is the sky,it is blue because of precipitation,green,blue,yellow,red,a,   
002,What color are my eyes,they are blue if you look,blue,brown,green,black,a,    
003,What color is the water,it is blue because of water,green,blue,red,yellow,b,

Why doesn't it work? 为什么不起作用? It's supposed to load in, the category ( 001 ), the question ( what color is the sky? ), and the choices for it ( green,blue,yellow,red ). 它应该加载,类别( 001 ),问题( what color is the sky? ),以及它的选择( green,blue,yellow,red )。 Is my regex off? 我的正则表达式了吗?

edit: a bit of context, this is the full code. 编辑:一点上下文,这是完整的代码。 Been trying suggestions from this thread with no success thus far. 从这个线程尝试的建议到目前为止没有成功。

package TestAssignment;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.border.Border;

public class TestGui extends JFrame implements ActionListener {

private int counter = 0;
private int totalCount = 0;
private JTextArea question = new JTextArea();
private JTextArea recomendedAnswer = new JTextArea();
private JTextArea category = new JTextArea();
private ArrayList<String> list;
private ArrayList<String> linesFromFile;
private int currentQuestion = 0;
private ButtonGroup group = new ButtonGroup();
private ArrayList<JRadioButton> theButtons;
private JLabel response = new JLabel("");
private JButton answer = new JButton("Answer Question");
private Border border = BorderFactory.createLineBorder(Color.BLACK, 1);
private Scanner scanner;
private String fileName;

public void readNextEntry() {

    list = new ArrayList<String>();

    scanner = new Scanner(linesFromFile.get(currentQuestion)).useDelimiter(",|\n");
    for (int i = 0; i < 8; i++) {
        list.add(scanner.next());
    }
}

public void readFile() {
    linesFromFile = new ArrayList<String>();
    list = new ArrayList<String>();
    try {

        scanner = new Scanner(new File(fileName));
        while (scanner.hasNextLine()) {
            linesFromFile.add(scanner.nextLine());
        }
        Collections.shuffle(linesFromFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

public TestGui(String in) {

    setLayout(new GridLayout(11, 25));
    this.fileName = in;

    add(new JLabel("Category : "));
    JScrollPane scrollPane1 = new JScrollPane(category);
    category.setLineWrap(true);
    category.setBorder(border);
    add(scrollPane1);
    category.setEditable(false);

    //int randomNumber = (int) (Math.random() * 10) + 1;
    //String line = TestGui.readFileByLine("Questions.txt", randomNumber);

    add(new JLabel("Question: "));
    JScrollPane scrollPane2 = new JScrollPane(question);
    question.setLineWrap(true);
    question.setBorder(border);
    add(scrollPane2);
    question.setEditable(false);

    readFile();
    readNextEntry();

    add(new JLabel("Please Select the correct Answer"));

    theButtons = new ArrayList<JRadioButton>();

    for (int i = 0; i < 4; i++) {
        JRadioButton temp = new JRadioButton();
        theButtons.add(temp);
        add(temp);
        group.add(temp);
    }
    refreshButtonLabels();

    add(response);

    category.setText(list.get(0));
    question.setText(list.get(1));

    add(answer);

    answer.addActionListener(this);
   }

  public void refreshButtonLabels() {
    for (int i = 0; i < 4; i++) {
        theButtons.get(i).setText(list.get(i + 3));
    }
  }

    @Override
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == answer) {
        for (int i = 0; i < theButtons.size(); i++) {
            JRadioButton button = theButtons.get(i);
            if (button.isSelected() && list.get(7).equals("a")) {
                counter++;
                readNextEntry();
            }
            else if (button.isSelected() && list.get(7).equals("b")){
                counter++;
                readNextEntry();
            }
             else if (button.isSelected() && list.get(7).equals("c")){
                counter++;
                readNextEntry();
            }
             else if (button.isSelected() && list.get(7).equals("d")){
                counter++;
                readNextEntry();

            }
        }
    }
     else {
           readNextEntry();
          {
    }
    }





package TestAssignment;

import javax.swing.JFrame;


public class Test {
public static void main(String[] args) {
    TestGui test = new TestGui();
    test.setVisible(true);
    test.setSize(600, 600);
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

You'll find it much easier to simply split the string on commas: 你会发现简单地在逗号上拆分字符串要容易得多:

String line = linesFromFile.get(currentQuestion);
String[] list = line.split(",\\s*");

The Scanner is just getting in your way. 扫描仪正在妨碍你。 But when you do use a Scanner, never call one of its nextXXX() methods without first calling the associated hasNextXXX() method. 但是,当你使用一个扫描仪, 永远不会调用它的一个nextXXX()方法,而没有先调用相关的hasNextXXX()方法。 For example: 例如:

while (scanner.hasNext())
{
  list.add(scanner.next());
}

Used correctly, Scanner should never throw a NoSuchElementException. 正确使用,Scanner永远不应抛出NoSuchElementException。

In theory this should work. 理论上这应该有效。 The confusing thing was working out the types of variables that are only hinted at in your snippet. 令人困惑的事情是计算出你的代码片段中仅提示的变量类型。

static List<String> linesFromFile = new ArrayList<String>();
static {
    linesFromFile.add("001,what color is the sky,it is blue because of precipitation,green,blue,yellow,red,a,");
    linesFromFile.add("002,What color are my eyes,they are blue if you look,blue,brown,green,black,a,");
    linesFromFile.add("003,What color is the water,it is blue because of water,green,blue,red,yellow,b,");
}

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();

    Scanner scanner = new Scanner(linesFromFile.get(1)).useDelimiter(",|\n");
    for (int i = 0; i < 8; i++) {
        list.add(scanner.next());
    }
    System.out.println(Arrays.toString(list.toArray()));
}

Prints [002, What color are my eyes, they are blue if you look, blue, brown, green, black, a] 打印[002, What color are my eyes, they are blue if you look, blue, brown, green, black, a]

Why are you delimitering by "\\n" if you have already have them separated by lines? 如果你已经用行分隔,为什么要用“\\ n”来划界? Seems like one of the lines doesn't have enough elements like you are expecting. 似乎其中一条线没有足够的元素,就像你期望的那样。 You should try outputting the line before getting the individual elements (or just debugging it). 您应该在获取单个元素之前尝试输出该行(或者只是调试它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM