java - read from a file i created with random ints and place into an array and display values
问题描述
a. Reopen the file for reading. b. Read each value from the file and place into an array. c. Display each value AFTER it is placed into the array (i.e. access value from array to display).
d. Find and display the largest two distinct numbers in the array. a. It is possible for the array to contain duplicates which causes 1st largest = 2nd largest. b. Skip duplicates for 2nd largest! See tips section for details. e. Sort the array into descending order (largest to smallest). When performing this sort: a. You can use the sort method in the Arrays class b. You cannot use the reverseOrder method on the Collections class c. You must manually sort the values into descending order. d. Manually sorting means you must write the code that does the sorting without using any methods other than Arrays.sort() f. Display the updated array after manually sorting into descending order.
I have tried using different methods even though it is not necessary for this problem. When I try and compile all I get for my array is [] and no values.
int max = 100;
int min = 1;
Random randomNum = new Random();
File fileName = new File("assignment1.txt");
PrintWriter resultsFile = new PrintWriter (fileName);
System.out.println("Generating random values and writing to a file: ");
for(int i = 1; i < 26; i++) {
int showMe = min + randomNum.nextInt(max);
System.out.println("Writing to a file: ");
System.out.println(showMe);
resultsFile.println(showMe);
}
resultsFile.close();
System.out.println("Reading values from file and placing into an array");
int[] data = readFiles("assignmnent1.txt");
System.out.println(Arrays.toString(data));
}
public static int[] readFiles(String fileName) {
try {
//File f = new File(fileName);
Scanner s = new Scanner (fileName);
int ctr = 25;
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
int [] arr = new int[ctr];
return arr;
}
catch (Exception e) {
return null;
}
I am not sure where I am going wrong and why it will not display the values in the array.
解决方案
在您的 readFiles 函数中,您初始化了数组,但没有用任何值填充它。
int [] arr = new int[ctr];
return arr;
推荐阅读
- java - 如何中断从输入流中读取
- unix - 使用键/连接列中的重复条目执行完全外连接的命令
- rascal - 如何在流氓中以毫秒为单位获取当前时间
- math - OpenGL:使用四元数从位置和方向获取lookAt中心
- matlab - 表中的散点图 - Matlab
- powershell - 使用 Out-GridView 选择对象
- jquery - 使用 JSON & JQUERY 返回数据
- google-colaboratory - 如何在上传的笔记本上保留单元格输出?
- excel - 1004 错误:无法获取 WorksheetFunction 类的 StDev_S 属性
- php - Yii2 验证,允许几种不同的格式