Android Studio新手代码报错求助:return位置错误与方法未找到
Hey there! Let's work through those errors you're facing with your fact generator app. I'll break down each issue and show you the corrected code step by step.
First: The return outside method Error in Facts.java
This error pops up because you tried to use a return statement inside an instance initialization block (the code wrapped in {} after your variable declarations) instead of a proper method. You also made two other critical mistakes here:
- You declared
nextFactas an array (public String nextFact[];) instead of a method that returns a single String. - Your array is named
Facts(uppercase F), but you tried to returnfacts(lowercase f)—Java is case-sensitive, so these are treated as completely different variables.
Second: The cannot find symbol method nextFact() Error in MainActivity.java
This is just a side effect of the first problem—your Facts class didn't actually have a nextFact() method defined. Once we fix the Facts class, this error will disappear automatically.
Corrected Code
Facts.java
package com.example.me.myapplication; public class Facts { // Renamed to lowercase for standard Java naming conventions private String[] facts = { "This is Fact 1", "This is fact 2", "This is fact 3", }; private int i = -1; // Start at -1 so first increment lands on index 0 // Proper method definition for nextFact() public String nextFact() { i++; // Loop back to the first fact when we reach the end of the array if (i >= facts.length) { i = 0; } return facts[i]; } }
MainActivity.java
Your MainActivity code is actually totally fine! The only issues were in the Facts class. Here it is again for reference:
package com.example.me.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView factBox; Facts factHolder = new Facts(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); factBox = (TextView) findViewById(R.id.factTextBox); } public void genFact(View view) { factBox.setText(factHolder.nextFact()); } }
Key Changes Explained
- Renamed the array to
facts(lowercase) to follow Java's variable naming rules (variables start with lowercase letters). - Converted
nextFactfrom an array to a proper method (public String nextFact()) that returns a single String value. - Set
ito-1initially so the first call tonextFact()increments it to 0 (the first valid index of the array). - Added a check to loop back to the first fact when we reach the end of the array, preventing an
ArrayIndexOutOfBoundsExceptioncrash.
Once you replace your Facts.java with the corrected version, your app should compile and run without those frustrating errors. Give it a test run!
内容的提问来源于stack exchange,提问作者Kryton

