从控制台读取所有行并将其存储在A集合中。在这种情况下,如何使用扫描仪的方法。用户可以输入的行数未知。
答案 0 :(得分:1)
尝试一下:
Scanner reader = new Scanner(System.in);
List<String> a = new ArrayList<>();
while (reader.hasNextLine()) {
String s = reader.nextLine();
if (s.equals("!q")) {
break;
}
a.add(s);
}
答案 1 :(得分:1)
您可以尝试以下操作:
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
输出将是:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0