可以解释一下为什么当我在android模拟器上部署它时这个代码不能正常工作
public class towers extends Activity {
/** Called when the activity is first created. */
private EditText text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
static int moves = 0;
static int totalDisks = 0;
public void myClickHandler(View view) throws java.io.IOException {
char fromPole = 'A';
char withPole = 'B';
char toPole = 'C';
switch (view.getId()) {
case R.id.editText1:
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter number of disks",
Toast.LENGTH_LONG).show();
return;
}
float disks = Float.parseFloat(text.getText().toString());
FileOutputStream fos = new FileOutputStream("TowersOfHanoiSolution.txt");
PrintStream ps = new PrintStream(fos);
solveHanoi(disks, fromPole, toPole, withPole, ps);
ps.close();
System.out.println();
text.setText("\nAmount of moves: " + moves + "\n");
}
}
static void solveHanoi(float disks, char start, char end, char intermediate, PrintStream ps) {
if (disks >= 1) {
solveHanoi(disks-1, start, intermediate, end, ps);
moveDisk(start, end, ps);
solveHanoi(disks-1, intermediate, end, start, ps);
}
}
static void moveDisk(char fromPole, char toPole, PrintStream ps) {
moves++;
if(totalDisks <= 10){
System.out.print("Move from " + fromPole + " to " + toPole + ". ");
ps.print("Move from " + fromPole + " to " + toPole + ". ");
if (moves%4 == 0){
System.out.println();
ps.println();
}
}
else {
ps.print("Move from " + fromPole + " to " + toPole + ". ");
if (moves%4 == 0){
ps.println();
}
}
}
}
答案 0 :(得分:1)
我将假设您的布局在myClickHandler
的{{1}}属性中声明android:onClick
,但最好包含您的布局以防止人们猜测。例如,如果editText1
处理程序连接不正确或根本没有连接,您将收到另一个例外,或者什么都不会发生。
但我会假设该方法被正确调用。您尝试创建文件而未指定路径,因此它尝试打开onClick
并收到/TowersOfHanoiSolution.txt
,其原因是“只读文件系统”:
FileNotFoundException
您使用的是Eclipse吗?如果使用Eclipse进行调试,则可以在logcat窗口中获取类似上述的堆栈跟踪,并且还可以暂停执行以让您检查应用程序的状态。但是,只需观察Caused by: java.io.FileNotFoundException: /TowersOfHanoiSolution.txt (Read-only file system)
at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at java.io.FileOutputStream.<init>(FileOutputStream.java:144)
at com.example.towers.towers.myClickHandler(towers.java:49)
... 14 more
或Eclipse的LogCat窗口就可以更简单地查看异常是什么;关键信息是引用代码的第一个行号。
请注意,这不是主要的例外;主要的例外是框架抱怨adb logcat
调用失败。同样,这就是为什么在调试器中暂停执行可能过于复杂,并且只需读取logcat以查看所有异常是什么就更容易了。
无论如何:您无法在Android上onClick
创建文件;因为这是工作目录,你需要指定完整路径(我假设为SD卡)。像这样:
/