import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner line = new Scanner(System.in);
while (line.hasNextLine()) {
String line = line.nextLine();
int counter = 1;
System.out.println(counter +" "+line);
counter++;
}
}}
任务:每一行都包含一个非空字符串。阅读直至EOF。 对于每一行,打印行号后跟一个空格和行内容。
示例输入: 你好世界
我是档案
请读到我,直到文件结束。
示例输出: 1 Hello world
2我是档案
3读完我,直到文件结束。
答案 0 :(得分:2)
Documentation
表示您需要将Source
传递给Scanner,以便它可以从中进行扫描。
要获得用户输入,您需要使用Scanner(InputStream source)
构造函数。
Scanner line = new Scanner(System.in);
public static void main(String[] args) {
Scanner line = new Scanner(System.in); // Added source parameter in constructor.
int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
while (line.hasNextLine()) {
String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable can't be declared with the same name in a method.
System.out.println(counter + " " + lineStr);
counter++;
}
}
注意:请确保break
使用while循环,否则它将进入infinite
循环。
答案 1 :(得分:2)
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments.
// You need to specify the environment in which you wish to 'scan'. Is it the IDE? A file? You need to specify that.
既然您说过EOF,我假设有一个与此任务相关的文件。
创建一个File对象,将其抛入Scanner构造函数。
File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);
您还有一个名为:line
的重复局部变量我建议你做更多的阅读,以掌握变量和对象的工作方式,而不是猜测或者是你不理解的勺子代码。这就是你成为一名优秀程序员的方式。
答案 2 :(得分:1)
如果您想从文件中扫描,可以使用以下代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("input.txt"));
int counter = 1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
答案 3 :(得分:1)
line
变量。尝试:
public class Solution {
public static void main(String[] args) {
//create the File
File file = new File(filename);
//send the file into Scanner so it can read from the file
Scanner scanner = new Scanner(file);
//initialize the counter variable
int counter = 1;
//read in the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(counter +" "+ line);
counter++;
}
}
}
答案 4 :(得分:0)
要阅读用户输入,您需要在代码中System.in
对象的声明中使用line
:
Scanner line = new Scanner(System.in);
int counter = 0; // Initialized out of loop.
while (line.hasNextLine()) {
String ln = line.nextLine();
System.out.println(counter +" "+ln);
counter++;
}