如何将一个分数分成两个整数?

时间:2014-04-11 06:54:03

标签: java fractions

我正在开发一个程序,我需要从包含分数的外部文件创建一个对象列表。我需要将分子和分母分成两个单独的整数,而不涉及“/”。

这是我到目前为止所做的:

while (fractionFile.hasNextLine()){

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

    }

我无法弄清楚如何在“/”之前读取num.add,并在“/”之后读取den.add

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

答案 2 :(得分: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
}

答案 3 :(得分: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]));
    }

答案 4 :(得分: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();
        }
    }
相关问题