简体   繁体   English

从Java中的文本文件读取字符串和整数

[英]reading string and integers from a text file in java

/*This assignment is to create 2 parallel arrays – jobs& salaries
*Read file from “careers.txt” into arrays
*one line – job
*next line –salary
*Sort Salaries {from highest}
*then swap jobs if salary swapped
*Display output of careers and salaries from the highest on a formatted table.
* 
 */
package assignment7;
import java.util.*;//importing Scanner


public class Coordinator 
{


    public static void main(String[] args) throws Exception
    {// the main method creates the arrays and calls on each method to perform 
        //its work.
     String [] job = new String[20];//creating a string array having 20 spaces
     int[] salary = new int[20];//creating an integer array having 20 spaces
     int count;// number of spaces actually occupied in the array

     **count = readFile(job, salary);**// calling a method to read text into both
                                   //arrays and return the number of spaces 
                                   //occupied in the array

     sorter(job,salary,count);// calling on method to arrange file from highest
     //to lowest

     display(job, salary,count);// calling on method present the output


    }
    public static int readFile(String[] jobber, int[] salaro) throws Exception
    { // this method reads a text file and copies into arrays and also
        //returns the number of spaces occupied in the array
            int n = 0; //keeps track of number of times a line is fed into an 
            //array

            //set up a file class object linked up to the name of the file to 
            //be read
            java.io.File unread = new java.io.File("career.txt");

            // create a scanner instance to read the input from the file
            Scanner infile = new Scanner(unread);

            /*This while loop reads line of text into the arrays, it uses 
             * boolean
             * function hasNextLine() and the created scanner instance.
             */
            while (infile.hasNextLine() || infile.hasNextInt())
            {
                jobber[n] = infile.nextLine();
                **salaro[n] = infile.nextInt()**;
                n++;
            }//end while
            infile.close();//close scanner class
            return n;// return number of spaces filled

    }//end of readFile method


    public static void sorter(String[] jobestic, int[] salawe, int z) 
            throws Exception
    {// this method sorts the array from the highest paid job to the lowest.

      boolean swapped;// keeps track of when a swap takes place
      int i;// variable fo for loop
      int temp;// helps in swap
      String temp2;// helps in swap

      do
      {
          swapped = false;
          for (i= 0; i < z-1; i++)// a pass through the array
          {
              if (salawe[i+1] > salawe[i])
              // if the number before it is less they swap
              {
                  //swap starts
                  temp = salawe[i+1];
                  salawe[i+1] = salawe[i];
                  salawe[i] = temp;
                  //swaps the jobs too if the salary is swapped
                  temp2 = jobestic[i+1];
                  jobestic[i+1] = jobestic[i];
                  jobestic[i] = temp2;

                  swapped = true;
              }// end if


          }// end for

      } while (swapped);
   }// end sorter method

   public static void display(String[] jobo, int[] salary5 ,int k) throws Exception
   {

       //this method displays the output as a formatted table
       int i;
       System.out.printf("%-60s%15s%n", "Job", "Salary");





       for(i=0; i<k; i++)



           System.out.printf("%-60s%,15d%n", jobo[i], salary5[i]);

   }








}

Please Guys, what is wrong with this code? 拜托,这个代码有什么问题? I have racked my brain over and over and can't figure out what is wrong.... I ran this code but i keep getting errors... The errors always indicate the bolded lines. 我一遍又一遍地绞尽脑汁,无法弄清楚出什么问题了。...我运行了这段代码,但我不断收到错误信息。 The text file I'm trying to read from is below. 我尝试读取的文本文件如下。 I want to store the job titles in one array and the corresponding salaries in the other array. 我想将职称存储在一个数组中,并将相应的薪水存储在另一个数组中。 Like Parallel arrays. 像平行阵列。 Please what is wrong with the code? 请问代码有什么问题? I want to store the salaries as integers because i have format it as integers when I present the output. 我想将薪水存储为整数,因为当我显示输出时,我将其格式化为整数。 Thank you. 谢谢。

Computer and Information Research Scientists
102190
Computer and Information Analysts
80460
Computer Systems Analysts
79680
Information Security Analysts
86170
Software Developers and Programmers
87100
Computer Programmers
74280
Software Developers(Applications)
90060
Software Developers(Systems Software)
99000
Web Developers
62500
Database and Systems Administrators and Network Architects
76880
Database Administrators
77080
Network and Computer Systems Administrators
72560
Computer Network Architects
91000
Computer Support Specialists
48900
Computer User Support Specialists
46420
Computer Network Support Specialists
59090

The error: 错误:

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Scanner.java:909) 
at java.util.Scanner.next(Scanner.java:1530) 
at java.util.Scanner.nextInt(Scanner.java:2160) 
at java.util.Scanner.nextInt(Scanner.java:2119) 
at assignment7.Coordinator.readFile(Coordinator.java:56)
at assignment7.Coordinator.main(Coordinator.java:25)

This question, or its equivalent, seems to get asked every few days. 似乎每隔几天就会询问这个问题,或与之相当的问题。

When you call nextInt() , your scanner stops after the number. 当您调用nextInt() ,扫描仪将在数字之后停止。 Then when you call nextLine() immediately afterwards, you're actually reading the new-line character at the end of the line that had the number on. 然后,当您随后立即调用nextLine() ,您实际上是在读取nextLine()的行的末尾的换行符。 You're not reading the next line. 您没有阅读下一行。 So on the next iteration of the loop, you're calling nextInt() when you've got non-numeric text lined up next in your scanner. 因此,在循环的下一次迭代中,当扫描仪中接下来排列非数字文本时,您将调用nextInt()

Add an extra call to nextLine() after every call to nextInt() , just to read that extra new-line character. 在对nextInt()每次调用之后添加一个对nextLine()的附加调用,只是为了读取该额外的换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM