Java读取.txt文件并以ASCII格式求和字符串/整数值

时间:2018-12-31 20:39:31

标签: java ascii

我需要加载包含字符串和整数的.txt 文件。 加载后,程序将打印使用一种方法(我已经写过)计算出的 ASCII 值的总和。 我的问题是所有的字符串和int 求和。 必须对所有行求和,除外以ASCII码显示总和的最后一行。

注意:有2个组(颜色)具有相同的信息 This the file. In yellow is the sum of all the info in .txt 我的代码:

	System.out.println("Enter Path To File:");
	File fileName = new File("Game.txt");
	Scanner sFromFile = new Scanner(fileName);
	String size = sFromFile.nextLine();
	int sizeBoard = Integer.parseInt(size);System.out.println("Board size loading size= "+size+"X"+size);
	String team = sFromFile.next();
	// int numOfSoliders = sFromFile.nextInt();
	Point arrSol []= new Point[sizeBoard];for(
	int i = 0;i<arrSol.length;i++)
	{
		arrSol[i] = new Point(sFromFile);
		System.out.println("Solider created successfully!");
	}
	// int numOfDragon = sFromFile.nextInt();
	Point arrDragon[] = new Point[sizeBoard];for(
	int i = 0;i<arrDragon.length;i++)
	{
		arrDragon[i] = new Point(sFromFile);
		System.out.println("Dragon created successfully!");
	}

	// ALSO DID THE SAME TO OTHER GROUP...

	// THE LAST LINE READING INPUT
	int fileHashCode = sFromFile.nextInt();System.out.println("HashCode loading...\n Loaded hashCode= "+fileHashCode);

	// TRY USE STRING METHOD
	// while (sFromFile.hasNext()) {
	// String str = sFromFile.nextLine();
	// System.out.print(str + ". ");
	// }

	sFromFile.close();

	// ALSO TRY OUTSIDE METHOD

	public static String readFile(String fName) throws FileNotFoundException {

		File f = new File(fName);

		Scanner sFromFile = new Scanner(f);

		for (int i = 0; i < board.length; i++) {

			while (sFromFile.hasNext()) {

				String str= sFromFile.nextLine();
				String sum+=str;
				//	 System.out.print(str + ". ");
			}
		}
		sFromFile.close();
		return sum;
	}

1 个答案:

答案 0 :(得分:0)

这意味着对文本的前7行中的所有字符(换行符除外)求和。

证明

String input = "8\r\n" +
               "RED\r\n" +
               "8 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7\r\n" +
               "8 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7\r\n" +
               "BLUE\r\n" +
               "8 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7\r\n" +
               "8 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7\r\n" +
               "6139";
try (Scanner sc = new Scanner(input)) {
    int sum = 0;
    for (int i = 0; i < 7; i++)
        sum += sc.nextLine().chars().sum();
    System.out.println("Calculated: " + sum);
    System.out.println("Last line : " + sc.nextLine());
}

输出

Calculated: 6139
Last line : 6139