简体   繁体   中英

Is there a way to read and calculate data from a file in Java using methods?

In my class we're using methods to calculate data from a text file. If I had a file that looked exactly like this:

Bob
25
Molly
30
Dylan
10
Mike
65

Is there anyway to pull this data from a file and then send it to a method to calculate, and then return that calculation to display on main? I'm confused as to how Java would be able to skip each line and calculate the numbers instead of the persons name. I was thinking about using inputFile.nextDouble(); and inputFile.nextLine(); . But how would I be able to set a String read the lines in the text file if I'm supposed to readthose text file lines variables as doubles? Sorry for all of the questions, I've been stuck on this for a long time and it's driving me crazy >.

I recommend you to use an ArrayList to read the full file:

Scanner s = new Scanner(new File(//Here the path of your file));

int number;
String name;

ArrayList<String> list = new ArrayList<String>();

while (s.hasNext())
{
    list.add(s.nextLine());
}

Now you have all the lines of your file (as a String ) so now you can operate with the full data that it's inside.

Further, the numbers are in the even lines so you can use a loop to through all the lines and check if the line that you are using now it's even or not.

for(int i = 0; i < list.size(); i++)
{
   if(i%2 == 0)
   {
      number = Integer.parseInt(list.get(i));
      //You can use the references to your methods with this number
   }
   else
   {
     name = list.get(i);
   }
}

With the % you will get the rest of the division (I'm using a property of pairs numbers). With Integer.parseInt you will parse your String to int .

So now you will be able to use this numbers to operate or whatever you want.


EDIT: Here you have an example without using ArrayList . In this case I'm going to use nextLine() and nextInt() functions:

Scanner s = new Scanner(new File(//Here the path of your file));
int count = 0;
int number;
int name;

while(s.hasNext())
{
    if(i%2 == 0)
    {
        number = s.nextInt();
        s.nextLine();
        //You can use the references to your methods with this number
    }
    else
    {
        name = s.nextLine();
    }
    count = count + 1;
}

If you have doubts about why I'm using s.nextLine() after number without storing any value you can look my answer to this question: Why isn't the scanner input working?

I expect it will be helpful for you!

You should just alternately use nextLine() and nextInt()

Scanner sc=new Scanner(new File(/* Path to the file*/));
int i=0;
while(sc.hasNext())
{
    if(i==0)
    {
        name=sc.nextLine();
    }
    else
    {
        number=sc.nextInt();
    }
    i=1-i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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