英文:
Why am I not getting the correct output in ques of printing even and odd index character seperatly?
问题
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // Consume the newline character after reading the integer
for (int i = 0; i < n; i++) {
String name = sc.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < name.length(); j++) {
if (j % 2 == 0)
even = even + String.valueOf(name.charAt(j));
else
odd = odd + String.valueOf(name.charAt(j));
}
System.out.println(even + " " + odd);
}
英文:
This is the link to the question. I have written this code in java but I am not getting the correct output.Why?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
String name = sc.nextLine();
String even="";
String odd ="";
for(int j=0; j<name.length(); j++)
{
if(j%2==0)
even=even+String.valueOf(name.charAt(j));
else
odd=odd+String.valueOf(name.charAt(j));
}
System.out.println(even+" "+odd);
This is the error I am getting.
Input (stdin)
2
Hacker
Rank
Your Output (stdout)
// a blank space here.
Hce akr
Expected Output
Hce akr
Rn ak
答案1
得分: 1
你的 int n = sc.nextInt();
会消耗输入的整数(2),但是仍然会有一个换行符。
当你的循环第一次执行,并且你调用 String name = sc.nextLine();
时,它会消耗掉那个剩余的换行符(以及其他什么都没有)。因此,会出现空行。
为了解决这个问题,在读取了 n
之后,确保读取掉这个新的换行符。
另外,最后一条输入可能没有显示出来,因为你可能需要一个尾随的换行符(在输入中的“Rank”之后再加一个换行符)。
英文:
Your int n = sc.nextInt();
consumes the integer that's input (2), but there is a still a newline.
When your loop goes through the first time, and you call String name = sc.nextLine();
, it will consume that remaining newline (and nothing else). Hence, your blank line.
To get past that, make sure to read in the new line after you read in n
Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)
答案2
得分: 0
你的代码是正确的,但问题出在你的输入处理上。
如果你按照以下方式输入:
2
Hacker
Rank
那么你所期望的输出将不会像你在问题中提到的那样出现。
现在我简要告诉你问题出在哪里:---------
int n = sc.nextInt();
在这里,你输入了一个整数2,但是你只声明了一个字符串类型的变量。如果你选择输入2,你必须声明两个字符串类型的变量。
否则,只会处理一个字符串。
Hacker
Rank
这就是为什么你需要两个字符串变量,但是根据你的代码,只会编译并输出 "Hacker"。
你需要声明两个字符串变量。
英文:
your code is correct but the problem is in your input taking.
if u take this as a input
2
Hacker
Rank
then your excepted output never come as u mentioned in your question.
Now i tell u in brief about where is the problem:---------
int n = sc.nextInt();
here u take integer input 2 but you delare only one string type variable.u must declare 2string typr variable if u choose 2.
otherwise only 1 tring willl be handled .
Hacker
Rank
thatswhy u take 2 string variable bt according to ur code only hacker will be compiled and give the output.
u declare 2 string variable .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论