简体   繁体   中英

How to split a fraction into two Integers?

I'm working on a program where I need to create an object list from an external file containing fractions. I need to separate the numerator and denominator into two separate integers, without having the "/" be involved.

This is what I have so far:

while (fractionFile.hasNextLine()){

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

    }

I can't figure out how to have num.add read up until the "/" and have den.add read right after the "/"

Any help would be much appreciated.

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
}

Assuming that you have multiple fractions in your file seperated by a token (eg line brake, or ; ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM