java - 将整数文件读入数组和冒泡排序时遇到问题
问题描述
在编译之前我没有收到任何错误,一切都运行了,但我的输出应该是文本文件中的几个整数,而不是一堆随机字符和数字。我不确定出了什么问题,但我的任务是将整数文件读取到数组中,然后使用冒泡排序方法进行排序。输出结果如下: Sorted Array order: [I@42a57993Sorted Array order: [I@42a57993Sorted Array order: [I@42a57993. 就我而言,任何帮助都是很好的帮助。谢谢。
import java.io.File;
import java.io.FileNotFoundException;
public class Array {
public static void main(String[] args) {
int[] arr = new int[10];
int i = 0;
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the file name:");
String fileName = input.next();
Scanner readFile = new Scanner(new File(fileName));
while (readFile.hasNext()) {
try {
arr[i] = readFile.nextInt();
i++;
} catch (InputMismatchException e) {
readFile.next();
}
bubbleSort(arr);
System.out.print("Sorted Array order: " + arr);
input.close();
}}catch(FileNotFoundException e) {
System.out.println("Error occured");
e.printStackTrace();
}
}
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}}
解决方案
稍微修改了一下,似乎得到了正确的输出
package com.kanhaiyakumawat.stackoverflow;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
int[] arr = new int[10];
int i = 0;
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the file name:");
String fileName = input.next();
Scanner readFile = new Scanner(new File(fileName));
while(readFile.hasNext()) {
try {
arr[i] = readFile.nextInt();
i++;
} catch(InputMismatchException e) {
readFile.next();
}
}
bubbleSort(arr);
System.out.print("Sorted Array order: " + Arrays.toString(arr));
} catch(FileNotFoundException e) {
System.out.println("Error occured");
e.printStackTrace();
}finally {
input.close();
}
}
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j = 1; j < (n - i); j++) {
if(arr[j - 1] > arr[j]) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
}
输出是:
Enter the file name:/Users/kkumawat/githome/personal/practice/src/main/java/com/kanhaiyakumawat/stackoverflow/myfile.txt
Sorted Array order: [0, 0, 0, 0, 0, 0, 0, 0, 5, 10]
Process finished with exit code 0
推荐阅读
- javascript - 通过两个标签小部件作为下拉菜单在博客平台中搜索
- python - 第一次使用 lua 加载模型时,lua 文件中的 model:forward() 显示分段错误
- sql - 将日志转换为每天的平均用户数
- apache-spark - apache spark 独立调度程序 - 为什么驱动程序在“集群”模式下需要一个完整的核心?
- python - 一次分布嵌套列表一个元素
- javascript - jQuery for setting value of an input type with selected radio value
- webpack - Webpack:如何只导入所需的字体真棒图标?
- wordpress - Woocommerce 单产品页面挂钩
- machine-learning - fizyr 使用视网膜网络进行汽车损坏检测的过度拟合(回归和分类)
- mysql - 如何设置在TestContainers启动的Docker实例上运行的mysql全局变量