0

How to take input from User as String given the String Length

The problem link:

http://www.practice.geeksforgeeks.org/problem-page.php?pid=295

MyApproach:

I used Scanner for the task to take the number of testcases and then took the String length as input:

But I am confused how to take String of specified length.My search found that there is no method or constructor which can take string of specified length.

Can Anyone guide?

Below is my code:

 Scanner sc=new Scanner(System.in);
 int T=sc.nextInt();
 for(int i=1;i<=T;i++)
  {
    int Strlength=sc.nextInt();
    String strnew=sc.next(); //How to take Stringofspecified character
    ..........
     .........
   }
1
  • you would want to read every char separately or read the whole line (nextLine()) and then just use the first n characters. Commented Jan 19, 2016 at 14:00

4 Answers 4

2

You can't do that, you can simply force the user to reinsert the String if the length of the String does not match the given input.

 Scanner sc=new Scanner(System.in);
 int T=sc.nextInt();
 for(int i=1;i<=T;i++)
  {
    int Strlength=sc.nextInt();
    String strnew = null;
    while (strnew == null || strnew.size() != Strlength) {
      strnew = sc.next(); 
    }
    ..........
     .........
   }
Sign up to request clarification or add additional context in comments.

2 Comments

Zandanra Okay.Shouldn't the strnew.size()== Strlength) be equal?Then only we can take the input from user.
If you write strnew.size() == Strlength, you will execute the block of while each time the user insert a String of correct size. That is not what you want, you want to continue asking for user input until the input is correct. Once the user has inserted a String of length Strlength (strnew.size() == Strlength), the while loop will not execute anymore and you can perform your calculations
1

A way to do this is inserting some kind of test, e.g.:

String strnew;
do{
   strnew=sc.next(); //How to take Stringofspecified character
}
while(strnew.length() != Strlength);

1 Comment

we could merge this answer with Simone Zandara's answer (since he was faster), since they mostly do the same. do-while just saves us the null-check.
1
    String S = "";
    Scanner sc = new Scanner(System.in);
    int D = sc.nextInt();
    for(int i=0;i<D;i++) {
         S = S + sc.next();
    }
    System.out.println(S);

1 Comment

makes string of specific length
0

I figured out a way to do this.

Scanner sc = new Scanner(System.in);
int strLength = sc.nextInt();
sc.nextLine(); 
String strInput = sc.nextLine();
if(strInput.length()>strLength)
{
    str = str.substring(0, strlength);
}
// Now str length is equal to the desired string length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.