0

I am new in java and working on some example of string. I am taking a number of String I need and then for each string I am specified some length which also a input from user. Once i get length integer I am trying to get same length of String. If it is exceed or less then I am throwing error. But I stuck how to get this.

In few places I am getting java.util.InputMismatchException My Code :

package Test;
import java.util.Scanner;

public class TestInputString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
         int Num = sc.nextInt();
         for(int i=0; i<Num; i++){
             int length = sc.nextInt();
             String str1 = sc.next();

         }
    }

}

My Output should be like this. Ouput :

No. of String - 3

Length : 4
String : ABCD

Length : 5
String : ABCDE

Length : 6
String : ABCDF 
shanky singh
  • 971
  • 2
  • 9
  • 19

1 Answers1

1

Instead of : String str = sc.nextLine();

Use this : String str = sc.next();

Panda2109
  • 39
  • 9