Gok*_*Raj 3 java java.util.scanner
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=new String();
int x=sc.nextInt();
double y=sc.nextDouble();
s = sc.next();
System.out.println("String:"+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}
}
Run Code Online (Sandbox Code Playgroud)
它只扫描一个单词,请提出任何建议......
小智 12
你可以试试这段代码:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
Run Code Online (Sandbox Code Playgroud)
因为Scanner对象将读取其先前读取停止的行的其余部分.
如果该行没有任何内容,它只会消耗换行符并移动到下一行的开头.
双重声明后,你必须写: scan.nextLine();
s = sc.next();
Run Code Online (Sandbox Code Playgroud)
它只扫描一个单词,请提出任何建议......
这是next();打算做的.如果您想阅读多个单词,最简单的解决方案是阅读一行文字.例如
String s = sc.nextLine();
Run Code Online (Sandbox Code Playgroud)
如果您需要阅读多行文本,您需要制定一个策略来执行此操作,例如在循环中读取所有内容,直到您有一个空行.
注意:虽然答案类似于Scanner在使用next(),nextInt()或其他nextFoo()方法后跳过nextLine(),但不同之处在于您不会丢弃该行的其余部分,而是使用String归来的nextLine();
如果您期望输入
1 2.0 Hello World
Run Code Online (Sandbox Code Playgroud)
然后你想使用上面的建议,但是如果输入是在这样的多行上
1 2.0
Hello World
Run Code Online (Sandbox Code Playgroud)
nextLine()如上面的链接所示,您将需要使用额外的类来丢弃剩余的行.
小智 5
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
double y = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + y);
System.out.println("Int: " + x);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37284 次 |
| 最近记录: |