簡體   English   中英

如何將分數拆分為兩個整數?

[英]How to split a fraction into two Integers?

我正在開發一個程序,需要從包含分數的外部文件創建對象列表。 我需要將分子和分母分成兩個單獨的整數,而不必涉及“ /”。

這是我到目前為止的內容:

while (fractionFile.hasNextLine()){

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

    }

我不知道如何讓num.add讀到“ /”,如何讓den.add讀在“ /”之后

任何幫助將非常感激。

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

使用String類的split方法使用所需的模式分割字符串。

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
}

假設您的文件中有多個分數以令牌分隔(例如,行制動器或; ):

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

暫無
暫無

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

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