• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help wanted to put correct Loop type....  RSS feed

 
KiranKumar Gogineni
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a Java newbie and please help me improve this program.
I want to restrict the user to enter only a word less than 6 letters. If he enters more than 5 I have to make him try again. I tried to use while loop in various ways but I am getting errors. Could someone help me?


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class EchoUsingIOPackage
{
public static void main (String args[]) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
//I need to start a loop here so that I can rerun this part if the user enters more than 5 characters.
System.out.println("Type some word (less than 6 characters) here and I will repeat

it Three times! ");
String input = br.readLine();
//End loop here
System.out.println(input + " " + input + " " + input);
}
}

-Kiran
 
Nikhil Jain
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope this solves your query!!...

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class EchoUsingIOPackage {
public static void main(String args[]) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = br.readLine();
// Comments Starts here
/*
* input.length() >= 5: Checks whether the length of entered word.
* input.indexOf(" ") != -1: Checks the index of " ". (to refrain user from entering
* multiple words
*/
// Comments Ends here
while (input.length() >= 5 || input.indexOf(" ") != -1) {
System.out.println("Please enter a single word less than 6 characters");
input = br.readLine();
}
System.out.println("Output: " + input + " " + input + " "
+ input);
}
}
 
KiranKumar Gogineni
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Shashank. It is working fine. But I am not able to understand completly about indexOf function. Could you please explain me a little bit clearly.
Thanks again,
Kiran
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String's indexOf method is being used here to check for a space. If the user's input contains a space, then they have entered more than one word and this code would require them to re-enter. If no space is found, then indexOf will return -1, indicating that the input is a single word.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!