如何在Java中读取多行输入

24

我们的教授让我们使用Java做一些基本编程,他提供了一个网站让我们注册并提交问题。今天我需要完成一个例子,感觉自己走在正确的轨道上,但我只是无法解决剩下的部分。以下是实际的问题:

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

**Sample Output:**
2
4
100

下面是我目前为止得到的内容:

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

现在我总是得到答案为2,因为我只读取了一行,如何考虑所有的行?谢谢。

由于某些奇怪的原因,每次我想要执行时都会出现这个错误:

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.
无论我使用哪个答案版本,我都会得到这个错误,我该怎么办?
但是,如果我在Eclipse中运行它,选择“运行配置”>“程序参数”。
10 12
10 14
100 200

我没有任何输出

编辑

我已经有了一些进展,最初我遇到了编译错误,然后是运行时错误,现在我得到的是错误的答案,所以有人能帮我看看这个程序哪里出了问题吗:

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

1
你的教授有没有明确说明他期望你如何将输入传递到程序中?是通过命令行、从文件中读取还是在程序运行时键入? - Nate
@Nate 嗯,他给了我们一个网站http://uva.onlinejudge.org,所以我们在那里注册并给他我们的用户名,他希望我们每天解决一个问题,这是一件好事...而且由于我无法让这个例子在我的电脑上运行,所以没有提交的目的。我正在尝试解决的问题是“10055-勇敢的战士Hashmat”http://acm.uva.es/p/v100/10055.html - Gandalf StormCrow
10个回答

27

终于搞定了,我提交了13次但都因为各种原因被拒绝了,第14次 "裁判" 终于接受了我的答案,这就是它:

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

使用Scanner类正是我正在寻找的东西,非常感谢。 - Arindam Paul
br = new BufferedReader(new InputStreamReader(new FileInputStream("/home/prashank/Desktop/input.txt"))); 这也可能会救你一命。我经常用它来处理大量数据。 - Thinker

9

使用 BufferedReader,您可以像这样从标准输入读取:

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

2
许多学生练习使用 Scanner,因为它有多种解析数字的方法。我通常只是从一个成语化的面向行的过滤器开始:
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);
        }
    }
}

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
在你的代码中加入一点解释会更好。 - LoïcR

1

@Hank Gay,这不是来自文件,如果是的话很容易处理,而是来自控制台参数。 - Gandalf StormCrow
1
@Gandalf,你可以使用BufferedReader来完成这个任务。 BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); - Buhake Sindi

0

这对于获取多行输入很有用

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

0
你在命令行运行程序时遇到的问题是你没有在类文件后面加上".class"。
只要你在java可以找到.class文件的地方,java Practice 10 12应该就能正常工作。
类路径问题是另一个故事了。如果java仍然抱怨找不到你的类,请进入与你的.class文件相同的目录(看起来你没有使用包...)并尝试: java -cp . Practice 10 12

Practice.class是否在您执行java -cp . Practice 10 12命令的相同目录中? - Nate

0

最简单的方法是

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
    }

}

}


虽然这段代码片段可能解决了问题,但是包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议的原因。 - Ralf Stubner

-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)+"");
        }
    }
}

这个解决方案比上面的那个更有效率,因为它只需要 2.128 秒,而上一个需要 1.308 秒来解决这个问题。


由于这是一项教育性练习,因此无需进行性能改进。代码的可读性 > 性能! - Kuchi

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

        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接