英文:
Why the code prints the extra line in the beginning and also after accepting 2 string it takes 0 to 2 which is 3 iteration to print the output?
问题
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i <= n; i++) {
String s1 = "", s2 = "";
String str;
str = sc.nextLine();
int l = str.length();
for (int k = 0; k < l; k++) {
if (k % 2 == 0)
s1 = s1 + str.charAt(k);
else if (k % 2 != 0)
s2 = s2 + str.charAt(k);
}
System.out.println(s1 + " " + s2);
}
}
}
英文:
Why does this code print an extra line in the beginning, and also after accepting 2 strings it takes 0 to 2, which is 3 iterations to print the output?
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<=n;i++)
{ String s1="",s2="";
String str;
str= sc.nextLine();
int l=str.length();
for (int k=0;k<l;k++)
{
if (k%2==0)
s1=s1+str.charAt(k);
else if(k%2!=0)
s2=s2+str.charAt(k);
}
System.out.println(s1+" "+s2);
}
}
}
答案1
得分: 0
我稍微调整了你的解决方案。它应该可以工作。
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for (int i = 0; i < n; i++) {
String s1 = "", s2 = "";
String str;
str = sc.nextLine();
int l = str.length();
for (int k = 0; k < l; k++) {
if (k % 2 == 0)
s1 = s1 + str.charAt(k);
else if (k % 2 != 0)
s2 = s2 + str.charAt(k);
}
System.out.println(s1 + " " + s2);
}
sc.close();
编辑:
此外,你在迭代时多了一次(n+1)次。
英文:
I tweaked your solution a bit. It should work.
Scanner sc=new Scanner(System.in);
int n=Integer.parseInt(sc.nextLine());
for(int i=0;i<n;i++)
{ String s1="",s2="";
String str;
str= sc.nextLine();
int l=str.length();
for (int k=0;k<l;k++)
{
if(k%2==0)
s1=s1+str.charAt(k);
else if(k%2!=0)
s2=s2+str.charAt(k);
}
System.out.println(s1+" "+s2);
}
sc.close();
Edit:
Also, you were iterating (n+1) times
专注分享java语言的经验与见解,让所有开发者获益!
评论