1

Following is my code . It is a basic menu driven java program to utilize all the string functions. But, consisting of functions having more than one string the second string input is not being considered.

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:");
        }
    }
}

The error appears in case 3 and 5

Danielson
  • 2,459
  • 2
  • 25
  • 48
krishb591993
  • 183
  • 1
  • 4
  • 16

1 Answers1

3

When you do a n.nextInt() it doesn't include the new line character. So when you do n.nextLine() inside your switch, it just returns an empty string....

To Fix, include n.nextLine() just after your n.nextInt() statement to flush out the new line character.

Codebender
  • 13,431
  • 6
  • 40
  • 83