如何在Java中读取多行输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2296685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read input with multiple lines in Java
提问by Gandalf StormCrow
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:
我们的教授让我们用 Java 做一些基本的编程,他提供了一个网站和一切来注册和提交我们的问题,今天我需要做这个例子我觉得我在正确的轨道上,但我就是做不到找出其余的。这是实际问题:
**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
现在我总是得到答案,2
因为我正在阅读单行,我如何考虑所有行?谢谢你
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.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
但是,如果我在 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]));
}
}
}
}
采纳答案by Gandalf StormCrow
I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :
我终于收到了,提交了 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()));
}
}
}
回答by Hank Gay
Look into BufferedReader
. If that isn't general/high-level enough, I recommend reading the I/O tutorial.
调查一下BufferedReader
。如果这还不够通用/高级,我建议阅读I/O 教程。
回答by Péter T?r?k
Use BufferedReader
, you can make it read from standard input like this:
使用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]));
}
}
回答by trashgod
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:
很多学生练习都使用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);
}
}
}
回答by Nate
The problem you're having running from the command line is that you don't put ".class" after your class file.
您从命令行运行的问题是您没有在类文件后放置“.class”。
java Practice 10 12
java Practice 10 12
should work - as long as you're somewhere java can find the .class file.
应该可以工作 - 只要你在某个地方,java 可以找到 .class 文件。
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 仍然抱怨它找不到您的类,请转到与您的 .class 文件相同的目录(并且看起来您没有使用包...)并尝试 -
java -cp . Practice 10 12
java -cp . Practice 10 12
回答by Executor100
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.
这个解决方案比上面的解决方案效率更高,因为它占用了 2.128 并且需要 1.308 秒来解决问题。
回答by Refat Khan
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);
}
}
回答by Raghuveer Reddy
public class Sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
回答by Ashutosh K Singh
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
}
}
}
}
回答by Nasar
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;
}
}
}
}