我有一個檔案如下,但還有幾個名字(每個單詞和數字都在單獨的一行上):James 123 343 355 Kyle 136 689 680
我一直在嘗試將所有這些作為字串讀取,并使用 parseInt 將它們轉換為整數,因為我需要找到名稱后面的數字的平均值。但是它沒有用,我很好奇如何在 Java 中列印這個檔案。謝謝
uj5u.com熱心網友回復:
這是您要找的嗎?
import java.util.*;
public class Main
{
public static void main(String[] args) {
//System.in is a standard input stream
Scanner sc= new Scanner(System.in);
String name=sc.next();
int a= sc.nextInt();
int b= sc.nextInt();
int c= sc.nextInt();
int d=(a b c)/3;
System.out.println("Average= " d);
}
}
uj5u.com熱心網友回復:
讓我們假設在每個名稱下它們可以是可變數量的數值。我們想要做的是,雖然每一行都是數字,但不斷將它們加在一起并跟蹤我們已閱讀的行數,以及當該行變為String可能時將其列印出來并設定為下一個序列。
老實說,我認為人們認為這Scanner僅對讀取用戶輸入或檔案有用,而忘記了他們可以使用多個Scanners 來決議相同的內容(或提供幫助)
例如。我設定Scanner為讀取檔案的每一行(作為String)。然后我設定第二個Scanner(每行)并測驗它是否是一個int并采取適當的措施,例如......
import java.util.Scanner;
public class Test {
public static void main(String[] arg) {
// Just beware, I'm reading from an embedded resource here
Scanner input = new Scanner(Test.class.getResourceAsStream("/resources/Test.txt"));
String name = null;
int tally = 0;
int count = 0;
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner parser = new Scanner(line);
if (parser.hasNextInt()) {
tally = parser.nextInt();
count ;
} else {
if (name != null) {
System.out.println(name "; tally = " tally "; average = " (tally / (double) count));
}
name = parser.nextLine();
tally = 0;
count = 0;
}
}
if (name != null) {
System.out.println(name "; tally = " tally "; average = " (tally / (double) count));
}
}
}
根據您的示例資料,列印出類似...
James; tally = 821; average = 273.6666666666667
Kyle; tally = 1505; average = 501.6666666666667
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369085.html
上一篇:org.jetbrains.skiko.LibraryLoadException:找不到libskiko-macos-arm64.dylib.sha256,缺少正確的本機依賴項
下一篇:未找到ID的視圖
