0

ストリングの交換に問題があります。

これは Question クラスのメソッドです。

public class Question
{
private String text;
private String answer;

/**
Constructs a question with empty question and answer.
 */
public Question(String qText) 
{
    text = qText;
    answer = "";
}

/**
Sets the answer for this question.
@param correctResponse the answer
 */
public void setAnswer(String correctResponse)
{
    answer = correctResponse;
}

/**
Checks a given response for correctness.
@param response the response to check
@return true if the response was correct, false otherwise
 */
public boolean checkAnswer(String response)
{
    return response.equals(answer);
}

/**
Displays this question.
 */
public void display()
{
    System.out.println(text);
}
}

そして、これが私の方法です

This is my blankQuestions class

import java.util.ArrayList;  


public class BlankQuestion extends Question {  

public BlankQuestion(String qText) {   
    return qText.replaceAll("_+\\d+_+", "_____");


    String tempSplit[] = questionText.split("_");  
    setAnswer(tempSplit[1]);  

}  
public void setAnswer(String correctChoice){  
    super.setAnswer( correctChoice );  

}  

@Override  
public boolean checkAnswer (String response){  
    return super.checkAnswer(response);  

}  

public String toString(){  
    return super.toString();  
}  


}  

これが私のメインクラスです

import java.util.Scanner;  

public class QuestionDemo  
{  
public static void main(String[] args)  
{  
  Question[] quiz = new Question[2];  

  BlankQuestion question0 = new BlankQuestion(  
     "2 + 2 = _4_");  
  quiz[0] = question0;  

  BlankQuestion question1 = new BlankQuestion(  
     "The color of the sky is _blue_.");  
  quiz[1] = question1;  

  Scanner in = new Scanner(System.in);  
  for (Question q : quiz)  
  {  
     q.display();  
     System.out.println("Your answer: ");  
     String response = in.nextLine();  
     System.out.println(q.checkAnswer(response));  
  }  
}  
}  

私が理解していることから、[underscore]4[underscore] を 5x[underscore] に置き換えます。これは空白を埋めるのと似ています。4 を保存し、文字列の一部を_ __ _ _に置き換えます。残念ながら、それが私の結果です。私の論理は正しいと思いますが、なぜ私のリターンが私が期待したものではないのか分かりません.

4

1 に答える 1

2

すべてを一度に行うだけです:

return qText.replaceAll("_+\\d+_+", "_____");

これは、1 つ以上のアンダースコアの後に 1 つ以上の数字が続き、その後に 1 つ以上のアンダースコアが続くものを 5 つのアンダースコアに置き換えます。

于 2013-05-05T06:09:48.243 に答える