Android Studio报‘class’ or ‘interface’ expected错误,代码在线编译正常
解决Android Studio中'class' or 'interface' expected错误
问题原因分析
你碰到的这个错误核心是代码结构违反了Java类的语法规则:你的onCreate方法被错误地放在了Activity2类的外部——看代码就能发现,在rand()方法结束后,你用一个}把Activity2类给闭合了,之后才写@Override和onCreate方法。Java里方法必须定义在类内部,所以编译器才会提示需要class或interface。
另外补充个小知识点:Android应用的启动入口不是main方法,而是Activity的生命周期方法(比如onCreate),你写的main方法在Android环境下根本用不上,可以直接移除;如果想留着做本地测试,也要确保它在类的内部。
修正后的代码
package com.tech.littlest.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.util.Random; public class Activity2 extends AppCompatActivity { // 注意:proposition_user数组有13个元素,这里常量要改成13,避免数组越界 final static int NO_DEDICATED_ARRAYS = 13; final static int NO_OUTPUT_SENTENCES = 1; final static String SPACER = " "; final static String PERIOD = "."; static Random r = new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_2); // 在Activity启动时调用生成句子的逻辑 generateRandomSentences(); } // 把原main方法里的逻辑抽成独立方法,便于在Android生命周期中调用 private void generateRandomSentences() { String proposition_user[] = { "You should build an invention that", "You should build a robot that", "You should create a whatchamacallit that", "There should be a device that", "Create a futuristic thing that", "Make a thing that", "Make something cool that", "I don't recall there being a thing that", "Create a sick thing that", "Devise a plan to create an object that", "I want a thing that", "If I just had a thingamajig that", "Create a thingimajig that"}; String plural_noun[] = { "children", "chickens", "the ocean", "cars", "apples", "houses", "water", "buildings", "people", "your friends", "farms", "the human race" }; String verb[] = { "directs you to", "drives on", "manages", "develops", "makes","eats", "helps", "relocates", "fixes", "feeds", "runs on", "washes" }; String sentence; for (int i = 0; i < NO_OUTPUT_SENTENCES; i++){ sentence = proposition_user[rand()]; char c = sentence.charAt(0); sentence = sentence.replace(c, Character.toUpperCase(c)); sentence += SPACER; sentence += verb[rand()]; sentence += SPACER + plural_noun[rand()]; sentence += PERIOD; // Android里用Log打印日志,替代System.out.println Log.d("RandomSentence", sentence); } } static int rand(){ int ri = r.nextInt() % NO_DEDICATED_ARRAYS; if (ri < 0) ri += NO_DEDICATED_ARRAYS; return ri; } }
额外优化提示
- 我帮你修正了
proposition_user数组里的拼写错误(and invention改成an invention、an thingamajig改成a thingamajig),同时把NO_DEDICATED_ARRAYS改成13,避免数组越界异常。 - Android环境下不要用
System.out.println输出内容,推荐用Log类打印日志,或者把生成的句子显示在界面的TextView组件中。
内容的提问来源于stack exchange,提问作者Aaron Kauffman
相关产品推荐
相关产品推荐

