【问题标题】:Java.lang.String[] as an incompatible type?Java.lang.String[] 作为不兼容的类型?
【发布时间】:2015-12-04 02:09:33
【问题描述】:
package com.example.mohammed.flagquizgameapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.lang.String;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
    // String used when logging error messages
    private static final String TAG = "FlagQuizGame Activity";

    private List<String> fileNameList; // flag file names
    private List<String> quizCountriesList; //name of countries in quiz
    private Map<String, Boolean> regionsMap; // which regions are enabled
    private String correctAnswer; // correct country for the current flag
    private int totalGuesses; // number of guesses made
    private int correctAnswers; // number of correct guesses
    private int guessRows; // number of rows displaying choices
    private Random random; //random number generator
    private Handler handler; // used to delay loading next flag
    private Animation shakeAnimation; // animation for incorrect guess

    private TextView answerTextView; // displays Correct! or Incorrect!
    private TextView questionNumberTextView; // shows current question #
    private ImageView flagImageView; // displays a flag
    private TableLayout buttonTableLayout; // table of answer Buttons

    // called when the activity is first created
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // call the superclass's method
        setContentView(R.layout.activity_main); // inflate the GUI

        fileNameList = new ArrayList<String>(); // list of flag names
        quizCountriesList = new ArrayList<String>(); // flags in this quiz
        regionsMap = new HashMap<String, Boolean>(); // HashMap of regions
        guessRows = 1; // default to one row of choices
        random = new Random(); // initialize the random number generator
        handler = new Handler(); // used to perform delayed operations

        // load the shake animation that's used for incorrect answers
        shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
        shakeAnimation.setRepeatCount(3); // animation repeats 3 times

        // get array of world regions from strings.xml
        String[] regionNames = getResources().getStringArray(R.array.regionsList);

        // by default, countries are chosen from all regions
        for (String region : regionNames)
            regionsMap.put(region, true);

        // get references to GUI components
        questionNumberTextView = (TextView) findViewById(R.id.questionNumberTextView);
        flagImageView = (ImageView) findViewById(R.id.flagImageView);
        buttonTableLayout = (TableLayout) findViewById(R.id.buttonTableLayout);
        answerTextView = (TextView) findViewById(R.id.answerTextView);

        // set questionNumberTextView's text
        questionNumberTextView.setText(getResources().getString(R.string.question) + "1"
                + getResources().getString(R.string.of) + "10");

        resetQuiz(); // start a new quiz
    } // end method onCreate
    // set up and start the new quiz
    private void resetQuiz()
    {
        // use the AssetManager to get the image flag
        // file names for only the enabled regions
        AssetManager assets = getAssets(); // gets the app's AssetManager
        fileNameList.clear(); // empty the list

        try{
            Set<String> regions = regionsMap.keySet(); // get Set of regions

            // loop through each region
            for(String region: regions) //if region is enabled
            {
                if(regionsMap.get(region)) {
                    //get a list of all the flag image files in this region
                    String[] paths = assets.list(region);

                    for(String path: paths)
                        fileNameList.add(path.replace(".png", ""));

                } // end if
            } // end for
        }// end try
        catch(IOException e)
        {
            Log.e(TAG, "Error loading image file names", e);
        } // end catch

        correctAnswers = 0; // reset the number of correct answers made
        totalGuesses = 0; // reset the total number of guesses the user made
        quizCountriesList.clear(); // clear prior list of quiz countries
    } // end method resetquiz

    // after the user guesses a correct flag, load the next flag
    private void loadNextFlag() throws IOException
    {
        // get the file name of the next flag and remove it from the list
        String nextImageName = quizCountriesList.remove(0);
        correctAnswer = nextImageName; // update the correct answer

        answerTextView.setText(""); // clear answerTextView

        // display the number of the current question in the quiz
        questionNumberTextView.setText(
               getResources().getString(R.string.question) + " " + (correctAnswers + 1) + " " +
               getResources().getString(R.string.of) + " 10");

        // extract the region from the next image's name
        String region = nextImageName.substring(0, nextImageName.indexOf('-'));

        // use AssetManager to load next image from the assets folder
        AssetManager assets = getAssets(); // get app's AssetManager
        InputStream stream; // used to read in flag images

        try{
            // get an InputStream to the asset representing the next flag
            stream = assets.open(region + "/" + nextImageName + ".png");]

            // load the asset as a Drawable and display on the flagImageView
            Drawable flag = Drawable.createFromStream(stream, nextImageName);
            flagImageView.setImageDrawable(flag);
        } // end try
        catch(IOException e)
        {
            Log.e(TAG, "Error loading " + nextImageName, e);
        } // end catch

        // clear prior answer Buttons from TableRows
        for(int row = 0; row < buttonTableLayout.getChildCount(); ++row)
            ((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();

        Collections.shuffle(fileNameList); // shuffle file names

        // put the correct answer at the end of fileNameList
        int correct = fileNameList.indexOf(correctAnswer);
        fileNameList.add(fileNameList.remove(correct));

        // get a reference to the LayoutInflater service
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        // add 3, 6, or 9 answer Buttons based on the value of guessRows
        for(int row = 0; row < guessRows; row++)
        {
            TableRow currentTableRow = getTableRow(row);

            // place Buttons in currentTableRow
            for(int column = 0; column < 3; column++)
            {
                // inflate guess_button.xml to create new button
                Button newGuessButton = (Button) inflater.inflate(R.layout.guess_button, null);

                // get country name and set it as newGuessButton's text
                String fileName = fileNameList.get((row*3) + column);
                newGuessButton.setText(getCountryName(fileName));

                // register answerButtonListener to respond to button clicks
                newGuessButton.setOnClickListener(guessButtonListener);
                currentTableRow.addView(newGuessButton);
            } // end for
        } // end for

        // randomly replace one Button with the correct answer
        int row = random.nextInt(guessRows); // pick random row
        int column = random.nextInt(3);// pick random column
        TableRow randomTableRow = getTableRow(row); // get the TableRow
        String countryName = getCountryName(correctAnswer);
        ((Button) randomTableRow.getChildAt(column)).setText(countryName);
    } // end method loadNextFlag

    // returns the specified TableRow
    private TableRow getTableRow(int row)
    {
        return (TableRow) buttonTableLayout.getChildAt(row);
    } // end method getTableRow

    // parses the country flag file name and reurns the country name
    private String getCountryName(String name) {
        return name.substring(name.indexOf('-') + 1).replace('_', ' ');
    } // end method getCountryName

    // called when the user selects an answer
    private void submitGuess(Button guessButton)
    {
        String guess = guessButton.getText().toString();
        String answer = getCountryName(correctAnswer);
        ++totalGuesses; // increment the number of guesses the user has made


        // if the guess is correct
        if(guess.equals(answer))
        {
            ++correctAnswers; // increment the number of correct answers

            // display "Correct!" in green text
            answerTextView.setText(answer + "!");
            answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));

            disableButtons(); // disable all answer Buttons

            // if the user has correctly identified 10 flags
            if (correctAnswers == 10)
            {
                // create a new AlertDialog Builder
                AlertDialog.Builder builder = new AlertDialog.Builder(this);

                builder.setTitle(R.string.reset_quiz); // title bar string

                // set the AlertDialog's message to display game results
                builder.setMessage(String.format("%d %s, %.02f%% %s", totalGuesses, getResources().getString(R.string.guesses),
                        (1000 / (double) totalGuesses), getResources().getString(R.string.correct)));

                builder.setCancelable(false);

                // add "Reset Quiz" Button
                builder.setPositiveButton(R.string.reset_quiz, new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog, int id)
                            {
                                resetQuiz();
                            } // end method onClick
                     } // end anonymous inner class
                ); // end call to setPositiveButton

                //create AlertDialog for the Builder
                AlertDialog resetDialog = builder.create();
                resetDialog.show(); // display the Dialog
            } // end if
            else // answer is correct but quiz is not over
            {
                  // load the next flag after a 1-second delay
                handler.postDelayed(
                        new Runnable(){
                            @Override
                            public void run()
                            {
                                loadNextFlag();
                            }
                        }, 1000); // 1000 milliseconds for 1-second delay
            } // end else
        } // end if
        else // guess was incorrect
        {
            // play the animation
            flagImageView.startAnimation(shakeAnimation);

            // display "Incorrect!" in red
            answerTextView.setText(R.string.incorrect_answer);
            answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
            guessButton.setEnabled(false); // disable the incorrect answer
        } // end else
    } // end method submitGuess

    // utility method that disables all answer Buttons
    private void disableButtons()
    {
        for(int row = 0; row < buttonTableLayout.getChildCount(); ++row)
        {
            TableRow tableRow = (TableRow) buttonTableLayout.getChildAt(row);
            for(int i = 0; i < tableRow.getChildCount(); ++i)
                tableRow.getChildAt(i).setEnabled(false);
        } // end outer for
    } // end method disableButtons

    // create constants for each menu id
    private final int CHOICES_MENU_ID = Menu.FIRST;
    private final int REGIONS_MENU_ID = Menu.FIRST + 1;

    // called when the user accesses the options menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);

        // add two options to the menu - "Choices" and "Regions"
        menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
        menu.add(Menu.NONE, REGIONS_MENU_ID, Menu.NONE, R.string.regions);

        return true; // display the menu
    } // end method onCreateOptionsMenu


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // switch the men id of the user-selected option
        switch(item.getItemId())
        {
            case CHOICES_MENU_ID:
                // create a list of the possible numbers of animal choices
                final String[] possibleChoices = getResources().getString(R.array.guessesList);

                //
        }
        return true;
    }
}

上面的代码在 switch 语句中有一个 String[]。我从这段代码中得到的错误如下:

不兼容的类型 必需:java.lang.String[] 找到:java.lank.String

我对此感到很困惑。我尝试在网上搜索它,但只得到 java.lang.string 找到但需要 int 的结果。

【问题讨论】:

  • 为什么要发200行不相关的代码?
  • 您在预期数组的位置传递了一个字符串。如果您只想传递一个字符串,请传递一个大小为 1 的数组,其中包含该字符串。
  • 我放了整个代码,因为根据过去的经验,如果我在代码的极性方面犯了一个小错误,它会改变整个结果。只是预防措施..
  • 只是预防措施表示您没有做出必要的努力来识别错误。请参观并阅读帮助中心,了解我们对 Stack Overflow 的期望。阅读How to ask
  • 原来问题不在于我确实经历过的其余代码。我不是专业人士,而你们是专业人士,所以我只需要仔细检查一下。无论如何感谢您的链接。

标签: java android android-studio


【解决方案1】:

改变

final String[] possibleChoices = getResources().getString(R.array.guessesList);

final String[] possibleChoices = new String[] { getResources().getString(R.array.guessesList)};

需要不兼容的类型:java.lang.String[] 找到: java.lang.String

possibleChoices 对象需要一个数组,而不是 Integer

【讨论】:

  • 您因有耐心挖掘所有代码而获得支持
  • 好吧,我们是来帮忙的,所以……xD Plus 他确实指出错误在switch 语句中……
  • 这解决了这个问题。但后来我遇到了另一个问题,说 (R.array.guessesList) 是资源的错误用途。不要觉得有义务回答。感谢您的第一个答案。
  • @MohammedIbrahim 确保您使用 guessesList id 定义资源的 string-array
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多