gpt4 book ai didi

java - 来自用户的字符串输入在 case 语句中没有被接受?

转载 作者:行者123 更新时间:2023-11-29 05:03:32 24 4
gpt4 key购买 nike

以下是我的代码。它是一个基本的菜单驱动的 java 程序,可以利用所有的字符串函数。但是,由具有多个字符串的函数组成,不考虑第二个字符串输入。

import java.util.*;

public class Strt {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner n = new Scanner(System.in);
String s1;
System.out.println("Enter a String:");
s1 = n.nextLine();
int choice;
System.out.println("Enter 1 for Length of the string\n Enter 2 to convert string to uppercase and lowercase \nEnter 5 to compare two strings \n Enter 4 to find substring of given string \n Enter 3 to concatenate two strings \nEnter 6 to get characters at given index");
choice = n.nextInt();
switch(choice){
case 1:
System.out.println("Length of the given string is"+ s1.length());
break;
case 2:
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
break;
case 3:
System.out.println("Enter another string:");
String s2 = n.nextLine();
System.out.println(s1.concat(s2));
break;
case 4:
System.out.println("Enter begin index and end index:");
int bInd = n.nextInt();
int eInd = n.nextInt();
System.out.println("Substring of given string is "+ s1.substring(bInd, eInd));
break;
case 5:
System.out.println("Enter another string to compare:");
String s3=n.nextLine();
boolean result = s1.equals(s3);
System.out.println(result);
break;
case 6:
System.out.println("Enter the index number:");
int index = n.nextInt();
System.out.println(s1.charAt(index));
break;
default:
System.out.println("Enter appropriate option:");
}
}
}

错误出现在情况3和5

最佳答案

当您执行 n.nextInt() 时,它不包含换行符。因此,当您在 switch 中执行 n.nextLine() 时,它只会返回一个空字符串....

修复,在 n.nextInt() 语句之后包含 n.nextLine() 以清除换行符。

关于java - 来自用户的字符串输入在 case 语句中没有被接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31199055/

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