Shan Solo
Shan Solo

Reputation: 57

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.

Upvotes: 0

Views: 2683

Answers (5)

ifloop
ifloop

Reputation: 8386

Assuming that you have multiple fractions in your file seperated by a token (e.g. 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]));
    }

Upvotes: 0

CHOCKO
CHOCKO

Reputation: 109

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
}

Upvotes: 0

Hirak
Hirak

Reputation: 3649

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

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3820

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

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

Use String class split method to split the string using the desired pattern.

Upvotes: 1

Related Questions