从文件中读取并将其插入数组,Java
我在这段代码中遇到运行时错误 我从文件中读取数据,将数据放入数组,然后使用插入排序算法对其进行排序并打印结果 什么导致我的运行时错误?这是运行时错误:java.util.InputMismatchException 以下是该文件包含的内容: 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318从文件中读取并将其插入数组,Java,java,Java,我在这段代码中遇到运行时错误 我从文件中读取数据,将数据放入数组,然后使用插入排序算法对其进行排序并打印结果 什么导致我的运行时错误?这是运行时错误:java.util.InputMismatchException 以下是该文件包含的内容: 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 743249861995247410594742333
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class InsertionSortExample {
private static int [] arr1;
public static void main(String[]args){
String fileName = "Data.txt"; //adds file as string
try{
Scanner fileScan = new Scanner(new File(fileName));//looks at the file
while(fileScan.hasNextLine()){//while there is another line in the file
String inputLine = fileScan.nextLine(); //adds that line to a string
Scanner scan = new Scanner(inputLine); //looks at each line
for(int i = 0; i < inputLine.length(); i++){ //reads through the line
arr1[i] = scan.nextInt(); //adds each element to an array
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found. Check file name and location."); // if theres no dile itll say
System.exit(1);
}
insertionSort(arr1);//sorting array using insertion sort
for(int member:arr1){
System.out.print(member +" "); //prints out each element of the array
}
}
public static void insertionSort(int array[]) {
int n = array.length; //length of the array
for (int j = 1; j < n; j++) { //for each member of the array
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
}
import java.util.Scanner;
导入java.awt.*;
导入javax.swing.*;
导入java.io.*;
公共类InsertionSortExample{
私有静态int[]arr1;
公共静态void main(字符串[]args){
String fileName=“Data.txt”;//将文件添加为字符串
试一试{
Scanner fileScan=new Scanner(新文件(文件名));//查看文件
while(fileScan.hasNextLine()){//while文件中还有另一行
String inputLine=fileScan.nextLine();//将该行添加到字符串中
扫描器扫描=新扫描器(inputLine);//查看每一行
对于(inti=0;i-1)和&(array[i]>key)){
数组[i+1]=数组[i];
我--;
}
数组[i+1]=键;
}
}
}
我想我知道为什么。。对于int,数字的极限约为20亿。。或10位数字。你的数字要大得多。即使长也不会那么大。。也许改用BigInteger?但是您的排序功能需要更改。我看到您输入的第二行中有一个空格?那是打字错误吗?或者可能是关于这个的。@ChayneP.S。这是一个打字错误。你能指出哪一行出错吗?@ChayneP.S。在java.util.Scanner.throwFor(Scanner.java:864)中,我的文件的值之间没有空格,因此修复了运行时错误。我使用python遍历文件,并在文件中的每个数字之间添加空格。