0

我想连接两个两个字符串。

这是我的代码:

import java.io.*;
import java.util.*;

public class Solution { 

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";       
        Scanner scan = new Scanner(System.in);    
        int a; double b;  String c;
        a = scan.nextInt();
        b = scan.nextDouble();
        c = scan.next();
        System.out.println(i + a);
        System.out.println(d + b);
        String res = s.concat(c);
        System.out.println(res);       
        scan.close();
    }
} 

输入:

12
4.0
is the best place to learn and practice coding!

这个输出:

16
8.0
HackerRank is

输出

我尝试了我能想到的一切。

4

5 回答 5

0

编辑:

如果更改为nextLine(),则先前的输入不会使用换行符,因此您必须添加额外的scan.nextLine();.

在线查看演示


首先,声明c(ie String c) 和aand b(或者你做了但忘了把它放在你的帖子中?)

但是,您的问题是使用Scanner::next而不是Scanner::nextLine.

.next()来自文档

从此扫描器中查找并返回下一个完整的令牌。

.next()使用第一个标记,使用空格作为分隔符,这就是为什么你的输出是HackerRank is,假设你c持有类似is a great site.

解决方案

改变:

c = scan.next();c = scan.nextLine();

于 2018-09-21T12:42:45.117 回答
0

干得好..

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        double b = scan.nextDouble();
        scan.nextLine();
        String c = scan.nextLine();
        System.out.println(i + a);
        System.out.println(d + b);
        String res = s + c;
        System.out.println(res);
        scan.close();


    }
}

并查看以下结果: 成功接受结果:

这是因为 Scanner.nextInt 或 nextDouble 方法不会使用您输入的最后一个换行符,因此在下次调用 Scanner.nextLine 时会使用该换行符

于 2018-09-21T12:48:00.800 回答
0
import java.util.*;
import java.lang.*;
import java.io.*;

class ScannerDemo
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        double b = scan.nextDouble();
        scan.nextLine();
        String c = scan.nextLine();
        System.out.println(i + a);
        System.out.println(d + b);
        String res = s.concat(c);
        System.out.println(res);
        scan.close();
    }
}

您的输入需要是

12
4.0
is the best place to learn and practice coding!

输出将是:

16 8.0 HackerRank is the best place to learn and practice coding!
于 2018-09-21T12:55:23.753 回答
0

在扫描 c 之前扫描额外的一行。喜欢

scan.nextLine();
c = scan.nextLine();

因为在输入 c 之前按回车,需要一行输入。

于 2018-09-21T13:22:59.013 回答
-1
int a = scan.nextInt();
double b = scan.nextDouble();
String c = scan.next();

你必须像我一样定义这个变量

于 2018-09-21T12:50:23.720 回答