gpt4 book ai didi

java - Android/Java 将文本文件中的名称存储在 String 数组中,并将整数存储在 int 数组中

转载 作者:行者123 更新时间:2023-11-30 01:51:30 26 4
gpt4 key购买 nike

我正在 android studio 中处理 java 代码,我试图从文本文件中获取名称并将它们存储在字符串数组中,以及整数(测试分数)并将它们存储在整数数组中。由于老师的限制,我无法更改文本文件。文本文件位于 Assets 文件夹中。关于如何实现这一点的任何想法,我已经搜索过并可以找到类似的问题,但似乎没有任何适用于我的情况。谢谢!

文本文件内容为:

Name            Test1   Test2   Test3   Final
Adam Anderson 81 90 85 87
Ben Brown 77 80 68 94
Chris Cross 74 80 56 62
Don Dare 86 94 90 89
Eric Earl 96 93 90 98
Fred Foley 79 92 59 86
Gina Gray 80 83 95 87
Holly Hank 74 77 75 78
Ian Ingram 66 64 56 60
Jill Johnson 90 98 78 89

我目前的代码是:

import android.app.AlertDialog;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class App1Act1 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app1_act1);
int[] testScores;
String[] studentNames;


//error message
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

AssetManager am = getAssets();

try {
InputStream inputT = am.open("grades.txt");

for(i=0; i<11; i++){
studentNames[i] = //???
}

}

catch(FileNotFoundException e) {

dlgAlert.setMessage("File was not found, please import file and try again.");
dlgAlert.setTitle("Error Message...");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}

catch(IOException e){
dlgAlert.setMessage("Oops! Something happened!"); //in the tradition of windows 10
dlgAlert.setTitle("Error Message...");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}

finally {

}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_app1_act1, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

最佳答案

首先:

  • 确保正确打开文件。
  • 避免在第一行进行任何处理,因此只是一个标题行。
  • 使用string tokenizer用空格分割线。因此,您现在调用 hasMoreTokens() 时的第一个字符串将是名字,第二个调用将是姓氏,下一个调用将为您提供数值。
  • 使用 Integer.parseInt() 方法将字符串转换为 int。

当然这只是一种方法,我相信你可以做一些比我的建议更好的事情。

关于java - Android/Java 将文本文件中的名称存储在 String 数组中,并将整数存储在 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com