24

Our professor is making us do some basic programming with Java, he gave 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 actual 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 every time 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.

Whatever 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])); 
            } 
        } 
    }
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263
  • 1
    Did your professor specify how he expects you to get the input into your program? From the command line, read from a file, typed into the program as it's running? – Nate Feb 19 '10 at 14:37
  • @Nate umm he gave us a website http://uva.onlinejudge.org so we register there give him our usernames, and he expects us to solve a problem each day which is a good thing.. and since I can't get this example to work on my computer there is no purpose of sumbitting it. The problem I'm trying to solve is `10055 - Hashmat the Brave Warrior` http://acm.uva.es/p/v100/10055.html – Gandalf StormCrow Feb 19 '10 at 14:41

10 Answers10

27

I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :

import java.io.BufferedInputStream;
import java.util.Scanner;

public class HashmatWarrior {

    public static void main(String args[]) {
        Scanner stdin = new Scanner(new BufferedInputStream(System.in));
        while (stdin.hasNext()) {
            System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
        }
    }
}
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263
  • Using Scanner class is the exact thing I was looking for, thanks a lot – Arindam Paul Mar 29 '12 at 18:31
  • br = new BufferedReader(new InputStreamReader(new FileInputStream("/home/prashank/Desktop/input.txt"))); this could also save the day. I used it often for heavy data. – Thinker Aug 18 '18 at 09:41
9

Use BufferedReader, you can make it read from standard input like this:

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]));
    }
}
Péter Török
  • 114,404
  • 31
  • 268
  • 329
2

A lot of student exercises use Scanner because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:

import java.io.*;

public class FilterLine {

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

        while ((s = in.readLine()) != null) {
            System.out.println(s);
        }
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2
 public class Sol {

   public static void main(String[] args) {

   Scanner sc = new Scanner(System.in); 

   while(sc.hasNextLine()){

   System.out.println(sc.nextLine());

  }
 }
}
1

Look into BufferedReader. If that isn't general/high-level enough, I recommend reading the I/O tutorial.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
0

The problem you're having running from the command line is that you don't put ".class" after your class file.

java Practice 10 12

should work - as long as you're somewhere java can find the .class file.

Classpath issues are a whole 'nother story. If java still complains that it can't find your class, go to the same directory as your .class file (and it doesn't appear you're using packages...) and try -

java -cp . Practice 10 12

Nate
  • 16,748
  • 5
  • 45
  • 59
  • Is Practice.class in the same directory you're executing `java -cp . Practice 10 12` from? – Nate Feb 19 '10 at 16:20
0

The easilest way is

import java.util.*;

public class Stdio4 {

public static void main(String[] args) {
    int a=0;
    int arr[] = new int[3];
    Scanner scan = new Scanner(System.in);
    for(int i=0;i<3;i++)
    { 
         a = scan.nextInt();  //Takes input from separate lines
         arr[i]=a;


    }
    for(int i=0;i<3;i++)
    { 
         System.out.println(arr[i]);   //outputs in separate lines also
    }

}

}

  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Ralf Stubner Jul 03 '18 at 16:15
0

This is good for taking multiple line input

import java.util.Scanner;
public class JavaApp {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String line;
        while(true){
            line = scanner.nextLine();
            System.out.println(line);
            if(line.equals("")){
                break;
            }
        }
    }  
}
Nasar
  • 66
  • 1
  • 8
-1
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String arg[])throws IOException{
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        StringTokenizer st;
        String entrada = "";

        long x=0, y=0;

        while((entrada = br.readLine())!=null){
            st = new StringTokenizer(entrada," ");

            while(st.hasMoreTokens()){
                x = Long.parseLong(st.nextToken());
                y = Long.parseLong(st.nextToken());
            }

            System.out.println(x>y ?(x-y)+"":(y-x)+"");
        }
    }
}

This solution is a bit more efficient than the one above because it takes up the 2.128 and this takes 1.308 seconds to solve the problem.

thkala
  • 84,049
  • 23
  • 157
  • 201
  • Since this is a Educational exercise there is no need to do performance improvement. Code readability > performance! – Kuchi Oct 11 '15 at 22:50
-2
package pac001;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Entry_box{



    public static final String[] relationship = {"Marrid", "Unmarried"};


    public static void main(String[] args)
    {
         //TAKING USER ID NUMBER
            int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
        // TAKING INPUT FOR RELATIONSHIP
        JFrame frame = new JFrame("Input Dialog Example #3");
        String Relationship =   (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
                                JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);



        //PRINTING THE ID NUMBER
        System.out.println("ID no: "+a);
        // PRINTING RESULT FOR RELATIONSHIP INPUT
          System.out.printf("Mariitual Status: %s\n", Relationship);

        }
}
Baby Groot
  • 4,637
  • 39
  • 52
  • 71