以下是我的代码。它是一个基本的菜单驱动的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
中答案 0 :(得分:3)
执行n.nextInt()
时,它不包含换行符。
因此,当您在交换机内执行n.nextLine()
时,它只返回一个空字符串....
要修复,
在n.nextLine()
语句之后包括n.nextInt()
以清除新行字符。