没有得到预期的输出中
输入格式没有得到预期的输出中
- 第一行包含一个整数。
- 第二行包含一个double,。
- 第三行包含一个字符串,。
输出格式
打印两个整数的在第一行的总和,这两个双打的在第二行的总和(缩放到小数位),并且然后在第三行上的两个级联的字符串。这里是我的代码
package programs;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "Programs ";
Scanner scan = new Scanner(System.in);
int i1 = scan.nextInt();
double d1 = scan.nextDouble();
String s1 = scan.next();
int i2 = i + i1;
double d2 = d + d1;
String s2 = s + s1;
System.out.println(i2);
System.out.println(d2);
System.out.println(s2);
scan.close();
}
}
输入(stdin)
12
4.0
are the best way to learn and practice coding!
你的输出(stdout)
16
8.0
programs are
期望输出
16
8.0
programs are the best place to learn and practice coding!
任何帮助,将不胜感激!
Scanner.next()
读取下一个令牌。默认情况下,空格用作记号之间的分隔符,因此您只能得到输入的第一个单词。
听起来好像要读取整个行,因此请使用Scanner.nextLine()
。根据this question,您需要拨打nextLine()
一次以消耗double
之后的换行符。
// Consume the line break after the call to nextDouble()
scan.nextLine();
// Now read the next line
String s1 = scan.nextLine();
如果我使用Scanner.nextLine(),那么它也给我意想不到的输出。请检查出 –
@KetanGupta:你是什么意思的“请检查出来”?检查什么?你还没有告诉我们,你在说什么...... –
现在我得到这个12 4.0 8.0 方案,作为我的输出 –
您正在使用scan.next()
读取值每个空间分隔符。
但在这里,你需要阅读的完整产品线,以便使用
String s1 = scan.nextLine();
所有你需要做的是改变
String s1 = scan.next();
到
String s1 = scan.nextLine();
您需要使用scan.nextLine()
这将读取一个完整的行并以作为分隔符读取每个值。
package programs;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "Programs ";
Scanner scan = new Scanner(System.in);
int i1 = scan.nextInt();
double d1 = scan.nextDouble();
String s1 = scan.nextLine();
int i2 = i + i1;
double d2 = d + d1;
String s2 = s + s1;
System.out.println(i2);
System.out.println(d2);
System.out.println(s2);
scan.close();
}
}
这是伟大的,你在这里提供一个完整的计划 - 在未来,这将是很好,如果你可以把它降低到最小的* *例子。鉴于阅读数字的位已经工作,你可以减少这基本上'扫描仪扫描=新扫描仪(System.in); String s1 = scan.next(); System.out.println(s1);' –
[Scanner](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next())将其输入分解为令牌**使用分隔符模式,默认情况下匹配空格** .. public String next() 查找并返回来自此扫描器的下一个完整令牌。**一个完整的标记前后有与分隔符**匹配的输入。即使先前调用hasNext()返回true,该方法也可能在等待输入进行扫描时阻塞。 – Tibrogargan
我看不出这个问题是怎么回事,+3,没有任何理由看到更好的问题与负面回购下去,似乎这家伙再次做了他的魔力。 –