无法从控制台获取完整的字符串输入
Unable to take full String input from console
public class PairsWithSumK
{
public static void main(String[] args) {
// Write your code here
Scanner sc= new Scanner(System.in);
int test= sc.nextInt();
for(int i=0;i<test;i++)
{
int num= sc.nextInt();
int sum= sc.nextInt();
String a;
a = sc.next();
String [] array= a.split(" ");
int count=0;
for(int j=0;j<num;j++)
{
int x=0;
x=sum-Integer.parseInt(array[j]);
String xs =String.valueOf(x);
if(Arrays.asList(array).contains(xs))
{
int index=Arrays.asList(array).indexOf(xs);
array[index]=array[j]="-1";
count++;
}
}
System.out.println(count);
}
}
}
我一直在尝试在 java 中获取控制台输入,但代码只获取第一个字符,而不是获取整行然后将其转换为字符串数组。例如:input-"1 2 3 4 5 6",字符串 "a" 只会取 1。作为编码的新手,我被困在了这里。
扫描器的 next() 方法只将字符串带到下一个分隔符(默认大小写为空格)。因此,在您的情况下,每次调用 auf sc.next() 都会读入您的一个号码(第一个,然后是第二个,等等)。
所以在您的代码中,您不会将它们作为字符串读入并拆分,而只是用 sc.next() 分别填充数组的每个索引。
(你可以使用sc.hasNext()来查看你是否已经添加了整个输入)。
默认情况下Scanner
我们使用作为分隔符一个或多个白色-spaces和next()
将尝试读取并且return 令牌直到下一个分隔符。因此,例如,如果您的输入是
1 2 foo bar
这样的代码将 return
nextInt(); // 1
nextInt(); // 2
next(); // foo
next(); // bar
注意第一个 next()
没有 return foo bar
只有 foo
因为后面有分隔符,所以没有 space分裂上。如果您想阅读其余部分,则需要使用 nextLine()
但是要小心该方法,因为如果您的输入是 1\nfoo
,您将调用 nextInt
和 nextLine
,您将得到 1
和 ""
(空字符串)作为结果,因为下一行尝试读取内容直到下一行分隔符或直到数据结束。因此,在 nextInt()
之后 1\nfoo
的情况下,光标将像 1|\nfoo
一样设置在 1
之后,因此在其当前位置和下一行分隔符 (\n
) 之间仅为空字符串.
public class PairsWithSumK
{
public static void main(String[] args) {
// Write your code here
Scanner sc= new Scanner(System.in);
int test= sc.nextInt();
for(int i=0;i<test;i++)
{
int num= sc.nextInt();
int sum= sc.nextInt();
String a;
a = sc.next();
String [] array= a.split(" ");
int count=0;
for(int j=0;j<num;j++)
{
int x=0;
x=sum-Integer.parseInt(array[j]);
String xs =String.valueOf(x);
if(Arrays.asList(array).contains(xs))
{
int index=Arrays.asList(array).indexOf(xs);
array[index]=array[j]="-1";
count++;
}
}
System.out.println(count);
}
}
}
我一直在尝试在 java 中获取控制台输入,但代码只获取第一个字符,而不是获取整行然后将其转换为字符串数组。例如:input-"1 2 3 4 5 6",字符串 "a" 只会取 1。作为编码的新手,我被困在了这里。
扫描器的 next() 方法只将字符串带到下一个分隔符(默认大小写为空格)。因此,在您的情况下,每次调用 auf sc.next() 都会读入您的一个号码(第一个,然后是第二个,等等)。
所以在您的代码中,您不会将它们作为字符串读入并拆分,而只是用 sc.next() 分别填充数组的每个索引。
(你可以使用sc.hasNext()来查看你是否已经添加了整个输入)。
默认情况下Scanner
我们使用作为分隔符一个或多个白色-spaces和next()
将尝试读取并且return 令牌直到下一个分隔符。因此,例如,如果您的输入是
1 2 foo bar
这样的代码将 return
nextInt(); // 1
nextInt(); // 2
next(); // foo
next(); // bar
注意第一个 next()
没有 return foo bar
只有 foo
因为后面有分隔符,所以没有 space分裂上。如果您想阅读其余部分,则需要使用 nextLine()
但是要小心该方法,因为如果您的输入是 1\nfoo
,您将调用 nextInt
和 nextLine
,您将得到 1
和 ""
(空字符串)作为结果,因为下一行尝试读取内容直到下一行分隔符或直到数据结束。因此,在 nextInt()
之后 1\nfoo
的情况下,光标将像 1|\nfoo
一样设置在 1
之后,因此在其当前位置和下一行分隔符 (\n
) 之间仅为空字符串.