gpt4 book ai didi

java - 为什么java中不能连续输入两个字符串?

转载 作者:行者123 更新时间:2023-12-02 11:42:07 25 4
gpt4 key购买 nike

我的程序在输入一个字符串后终止。它不需要字符串 2 输入。

这是代码片段:

    public static void main (String[] args) {
Scanner scn= new Scanner(System.in);
int T ;
T=scn.nextInt();
while(T!=0){
String s1 = scn.nextLine(); // after i give input for the first string ,program terminates!
String s2 = scn.nextLine(); // program terminates before asking for s2 input
System.out.println(isMetaString(s1,s2));
T--;
}
}

最佳答案

public static void main (String[] args) {
Scanner scn= new Scanner(System.in);
int T ;
T=scn.nextInt();

// scn.nextLine(); // for enter.
// here after entering int value,
// you must be pressing enter,
// that 'enter' is getting stored in s1,
// and then when you give first string it is getting stored in s2
// and that is why your program is terminating.

while(T!=0){
String s1 = scn.nextLine(); // after i give input for the first string ,program terminates!
String s2 = scn.nextLine(); // program terminates before asking for s2 input
System.out.println(isMetaString(s1,s2));
T--;
}
}

解决方案:在 sca.nextInt() 之后添加 sca.nextLine() 即可。将解决问题

关于java - 为什么java中不能连续输入两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com