有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从文件中读取并将其插入数组,Java

我在这段代码中遇到运行时错误

我从文件中读取数据,将数据放入数组,然后使用插入排序算法对其进行排序并打印结果

什么导致我的运行时错误?这是运行时错误:java。util。输入不匹配异常

以下是该文件包含的内容: 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318

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; 
    }
  }
}

共 (1) 个答案

  1. # 1 楼答案

    我想我知道为什么。。对于int,数字的极限约为20亿。。或10位数字。你的数字要大得多。即使长也不会那么大。。也许改用BigInteger?但是您的排序功能需要更改