how to read input with multiple lines in java

Posted by Gandalf StormCrow on Stack Overflow See other posts from Stack Overflow or by Gandalf StormCrow
Published on 2010-02-19T13:49:52Z Indexed on 2010/04/10 1:03 UTC
Read the original article Hit count: 533

Filed under:
|

Hi all,

Our professor is making us do some basic programming with java, he gaves a website and everything to register and submit our questions, for today I need to do this one example I feel like I'm on the right track but I just can't figure out the rest .. here is the actualy question :

**Sample Input:**
10 12
10 14
100 200

**Sample Output:**
2
4
100

And here is what I've got so far :

public class Practice {

    public static int calculateAnswer(String a, String b) {
        return (Integer.parseInt(b) - Integer.parseInt(a));
    }

    public static void main(String[] args) {
        System.out.println(calculateAnswer(args[0], args[1]));
    }
}

Now I always get the answer 2 because I'm reading the single line, how can I take all lines into account? thank you

For some strange reason everytime I want to execute I get this error:

C:\sonic>java Practice.class 10 12
Exception in thread "main" java.lang.NoClassDefFoundError: Fact
Caused by: java.lang.ClassNotFoundException: Fact.class
        at java.net.URLClassLoader$1.run(URLClassLoader.java:20
        at java.security.AccessController.doPrivileged(Native M
        at java.net.URLClassLoader.findClass(URLClassLoader.jav
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248
Could not find the main class: Practice.class.  Program will exit.

Whosever version of answer I use I get this error, what do I do ?

However if I run it in eclipse Run as > Run Configuration -> Program arguments

10 12
10 14
100 200

I get no output

EDIT

I have made some progress, at first I was getting the compilation error, then runtime error and now I get wrong answer , so can anybody help me what is wrong with this :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class Practice {

    public static BigInteger calculateAnswer(String a, String b) {
        BigInteger ab = new BigInteger(a);
        BigInteger bc = new BigInteger(b);
        return bc.subtract(ab);
    }

    public static void main(String[] args) throws IOException {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); 
        String line; 

        while ((line = stdin.readLine()) != null && line.length()!= 0) { 
            String[] input = line.split(" "); 
            if (input.length == 2) { 
                System.out.println(calculateAnswer(input[0], input[1])); 
            } 
        } 
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about homework