【问题标题】:String input from user not getting accepted inside case statement?来自用户的字符串输入在case语句中未被接受?
【发布时间】:2015-09-20 20:06:28
【问题描述】:

以下是我的代码。它是一个基本的菜单驱动的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出现错误

【问题讨论】:

标签: java


【解决方案1】:

当您执行n.nextInt() 时,它不包含换行符。 所以当你在你的开关里面做n.nextLine()时,它只会返回一个空字符串......

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

【讨论】:

  • 是的,正如之前提到的一百万次。
  • 是的,你的答案是正确的。它会解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
相关资源
最近更新 更多