2014-04-11 5 views
0

저는 분수가 들어있는 외부 파일에서 객체 목록을 만들어야하는 프로그램을 만들고 있습니다. 나는 분자와 분모를 "/"가 관여하지 않고 두 개의 분리 된 정수로 분리 할 필요가있다. 분수를 두 개의 정수로 나누는 방법은 무엇입니까?

내가 지금까지 무엇을 가지고 : 나는 "/"까지 읽어 num.add있는 방법을 알아낼 후 바로 읽을 den.add 수 없습니다

while (fractionFile.hasNextLine()){ 

    num.add(fractionFile.nextInt()); 
    den.add(fractionFile.nextInt()); 

    } 

은 "/"

도움을 주시면 감사하겠습니다.

+0

우리는이 포함 된 파일의 개요를 볼 수 있습니다 분수? – ifloop

답변

3
String fraction="1/2"; 
String []part=fraction.split("/"); 
num.add(part[0]) 
den.add(part[1]) 
+1

에서 전화를 두 번 호출하는 가장 효율적인 방법이 아닙니다 –

+0

동의 ... 올바른 ... –

+0

외부 파일에서 분수를 읽고 있어요. 2nd split을 어떻게 보내면 되겠습니까? –

1

String 클래스 split을 사용하여 원하는 패턴을 사용하여 문자열을 분할합니다.

+0

어떻게 할 수 있는지 설명해 주시겠습니까? –

+0

javadocs 내 대답은 –

0
while (fractionFile.hasNextLine()){ 
    //If file contains 
    // 1/2 
    // 2/4 
    // 5/6 
    String line = fractionFile.nextLine(); 
    String split[]=line.split("/"); 
    num.add(Integer.parseInt(split[0])); // 1 stored in num 
    den.add(Integer.parseInt(split[1])); // 2 stored in den 
} 
0

토큰로 구분 파일에 여러 개의 분수가 있다고 가정하면 (예 : 라인 브레이크, 또는 ;) :

String input   = "1/2;3/4;5/6"; 
    String token   = ";" 
    String[] currentFraction = null; 

    final List<Integer> nums = new LinkedList<>(); 
    final List<Integer> denoms = new LinkedList<>(); 

    for (String s : input.split(token)) { 
     currentFraction = s.split("/"); 
     if (currentFraction.length != 2) 
      continue; 

     nums.add(Integer.parseInt(currentFraction[0])); 
     denoms.add(Integer.parseInt(currentFraction[1])); 
    } 
0
BufferedReader br = null; 
    Integer num = 0; 
    Integer den = 0; 
    try { 

     String sCurrentLine; 

     br = new BufferedReader(new FileReader("test")); 

     while ((sCurrentLine = br.readLine()) != null) { 
      String [] str = sCurrentLine.split("/"); 
      if(str.length>2)throw new IllegalArgumentException("Not valid fraction..."); 

      num = num+Integer.parseInt(str[0]); 
      den = den+Integer.parseInt(str[1]); 
     } 

     System.out.println(num); 
     System.out.println(den); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    }