簡體   English   中英

有沒有一種方法可以使用Java從文件中讀取和計算數據?

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

在我的課程中,我們使用方法從文本文件計算數據。 如果我有一個看起來像這樣的文件:

Bob
25
Molly
30
Dylan
10
Mike
65

無論如何,是否有從文件中提取此數據,然后將其發送到要計算的方法,然后將該計算返回到主屏幕上顯示的方法? 對於Java如何能夠跳過每一行並計算數字而不是人員姓名,我感到困惑。 我在考慮使用inputFile.nextDouble(); inputFile.nextLine(); 但是,如果我應該將這些文本文件的行變量讀為double值,那么如何設置String來讀取文本文件中的行? 對不起所有問題,我已經堅持了很長時間,這讓我發瘋了>。

我建議您使用ArrayList讀取完整文件:

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

現在,您擁有了文件的所有行(作為String ),因此現在您可以使用其中的全部數據進行操作。

此外,數字位於偶數行中,因此您可以使用循環遍歷所有行,並檢查現在使用的行是否為偶數。

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

使用%您將獲得除法的其余部分(我使用的是對數屬性)。 使用Integer.parseInt您可以將String解析為int

因此,現在您將可以使用此數字進行操作或進行任何操作。


編輯:在這里您有一個示例,而不使用ArrayList 在這種情況下,我將使用nextLine()nextInt()函數:

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

如果您對為什么在number后不使用任何值的情況下使用s.nextLine()有疑問,可以看一下我對以下問題的回答: 掃描儀輸入為何不起作用?

希望對您有幫助!

您應該只交替使用nextLine()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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM