0

このコードについてサポートが必要です。入力は次のようなテキストファイルに保存されます。

最初:3 6
セコン:3 9

出力は次のとおりです。

First:3 6 

The Maximum number is6

The sum is9


Secon:3 9 


The Maximum number is9

The sum is12

しかし、私の希望する出力は次のようになります。

    The Maximum number is6
    The sum is12 

したがって、Math.max()は最初の行にのみ適用されます。そして、2行目の行番号を追加します。

助けてください。

import java.io.*;

public class cape 
{
 public static void main(String args[])
  {
  try{

  FileInputStream fstream = new FileInputStream("C:/Users/PC4599/Desktop/cape.txt"); // Open the text file.
  DataInputStream in = new DataInputStream(fstream);// Get the object of DataInputStream
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String MyString;


  //Read File Line By Line
  while ((MyString = br.readLine()) != null) 
  {

  // Print the content on the console
  System.out.println (MyString);


  Character c = new Character(MyString.charAt(6));
  Character c2 = new Character(MyString.charAt(8));



  String s = c.toString();
  String s2 = c2.toString(); 


  int i = Integer.parseInt(s);
  int i2 = Integer.parseInt(s2);

    int sum=i+i2;
  System.out.println("The Maximum number is"+ Math.max(i, i2));
  System.out.println("The sum is"+ sum);

  }
  //Close the input stream
  in.close();
  }catch (Exception e){
   //Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}
4

2 に答える 2

2

あなたはこれを行うことができます:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(new File("test.txt")));
    String[] nums1 = br.readLine().split(":")[1].split(" ");
    String[] nums2 = br.readLine().split(":")[1].split(" ");
    br.close();
    System.out.println("The maximum number is " + Math.max(Integer.parseInt(nums1[0]), Integer.parseInt(nums1[1])));
    System.out.println("The sum is " + (Integer.parseInt(nums2[0]) + Integer.parseInt(nums2[1])));    
}

ファイルに2行以上ある場合は、ループを使用して同様の方法を採用するのは難しくありません。

于 2012-09-04T21:56:44.260 に答える
1

行番号を数えて、各行の正しいものを出力できます。

int line = 0;
...
if (line == 0) System.out.println("The Maximum number is"+ Math.max(i, i2));
if (line == 1) System.out.println("The sum is"+ sum);
line++;
于 2012-09-04T21:45:33.053 に答える