How can I verify the int length of scanner input? - java

I was able to get the program to run and work with error checking to make sure that the user input is in fact an int. The issue I ran into is that I only want it to be a 3-digit int. I'm having trouble getting that into the right place:
import java.util.*;
public class listMnemonics
{
public static void main(String[] args)
{
//Defines the "keypad" similar to that of a phone
char[][] letters =
{{'0'},{'1'},{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},
{'M','N','O'},{'P','Q','R','S'},{'T','U','V'},{'W','X','Y','Z'}};
//Creates the Scanner
Scanner scan = new Scanner(System.in);
Right here is where I need to implement that and I am running into the issue. I'm sure it's maybe only a line out of place or missing that I need, I just don't know what or where. As it sits, it will constantly ask me to enter a 3-digit number, no matter the length. Error checking for a string entered does currently work:
//Gives instructions to the user to enter 3-digit number
//Any amount of numbers will work, but instructions help
//System.out.println("Please enter a 3-digit number: ");
int j;
do
{
System.out.println("Please enter a 3-digit number: ");
while (!scan.hasNextInt()) {
System.out.println("That's not a 3-digit number! Try again!");
scan.next(); // this is important!
}
j = scan.nextInt();
}
//while (j <= 0); This works while not checking digit length
while (j != 3);
int w = (int) Math.log10(j) +1; //Found this, but not sure if it helps or not
String n = Integer.toString(w);
And here is the rest that get's it to do what I need it to:
//Determines char length based on user input
char[][] sel = new char[n.length()][];
for (int i = 0; i < n.length(); i++)
{
//Grabs the characters at their given position
int digit = Integer.parseInt("" +n.charAt(i));
sel[i] = letters[digit];
}
mnemonics(sel, 0, "");
}
public static void mnemonics(char[][] symbols, int n, String s)
{
if (n == symbols.length)
{
System.out.println(s);
return;
}
for (int i = 0; i < symbols[n].length; i ++)
{
mnemonics(symbols, n+1, s + symbols[n][i]);
}
}
}
Here's the output:
----jGRASP exec: java listMnemonics
Please enter a 3-digit number:
2345
Please enter a 3-digit number:
12
Please enter a 3-digit number:
123
Please enter a 3-digit number:
motu
That's not a 3-digit number! Try again!

With the help of MvG and pingul, this is what is currently working the way I was hoping:
import java.util.*;
import java.util.regex.Pattern;
public class listMnemonics
{
public static void main(String[] args)
{
// Defines the "keypad" similar to that of a phone
char[][] letters =
{{'0'},{'1'},{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},
{'M','N','O'},{'P','Q','R','S'},{'T','U','V'},{'W','X','Y','Z'}};
// Creates the Scanner
Scanner scan = new Scanner(System.in);
// Gives instructions to the user to enter 3-digit number
// This 'Pattern' also guarantees that only 3 digits works.
Pattern threeDigitNumber = Pattern.compile("[0-9]{3}");
int j;
do
{
System.out.println("Please enter a 3-digit phone number: ");
// If it's not a 3-digit int, try again
while (!scan.hasNext(threeDigitNumber))
{
System.out.println("That's not a 3-digit number! Try again!");
// This is important!
scan.next();
}
j = scan.nextInt();
}
while (j <= 0);
String n = Integer.toString(j);
// Determines char length based on user input
char[][] sel = new char[n.length()][];
for (int i = 0; i < n.length(); i++)
{
// Grabs the characters at their given position
int digit = Integer.parseInt("" +n.charAt(i));
sel[i] = letters[digit];
}
mnemonics(sel, 0, "");
}
// Here is where the magic happens and creates the possible
// letter combinations based on the user input and characters
// selected in previous steps.
public static void mnemonics(char[][] symbols, int n, String s)
{
if (n == symbols.length)
{
System.out.println(s);
return;
}
for (int i = 0; i < symbols[n].length; i ++)
{
mnemonics(symbols, n+1, s + symbols[n][i]);
}
}
}

Condensed and reformatted your code reads
Scanner scan = new Scanner(System.in);
int j;
do {
System.out.println("Please enter a 3-digit number: ");
while (!scan.hasNextInt()) {
System.out.println("That's not a 3-digit number! Try again!");
scan.next(); // this is important!
}
j = scan.nextInt();
} while (j != 3);
Comparing that to the Scanner documentation we can see that the scan.next() call will read (and discard) the non-int token. Otherwise j will be the integer you read. And you continue doing so while the number you read is different from 3. Not the length of the number, but the number itself. So if you want to end the loop, enter 3. If you want to do so while following the prompt, enter 003.
If that's not what you want to check, then change the end of loop condition. Or perhaps change the way you test for three-digit numbers, by using regular expressions to match these.
Scanner scan = new Scanner(System.in);
Pattern threeDigitNumber = Pattern.compile("\\d\\d\\d");
int j;
System.out.println("Please enter a 3-digit number: ");
while (!scan.hasNext(threeDigitNumber)) {
if (scan.hasNext()) {
System.out.println(scan.next() + " is not a 3-digit number! Try again!");
} else {
System.out.println("Input terminated unepxectedly");
System.exit(1);
}
}
j = scan.nextInt();
As comments correctly indicate, the pattern "\\d\\d\\d" could just as well be written as "[0-9]{3}", or as "\\d{3}" or "[0-9][0-9][0-9]". Using {…} might be useful in situations where the number of digits is a variable.
The documentation for Scanner.hasNext(Pattern) requires the pattern to match the input. This apparently follows the Matcher.matches() semantics of matching the whole string against the pattern, as opposed to Matcher.find() which checks whether the string contains any part matching the pattern. So the input does not have to be enclosed in ^ and $, as I assumed at first, and in fact should not be using these unless the pattern is compiled with the Pattern.MULTILINE flag.
You may want to call Scanner.useDelimiter to delimit using line breaks only.
Scanner.useDelimiter("[\\r\\n]+")

Related

Java Sum of numbers until string is entered

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

Asking user to enter specific number of strings then adding each string to array?

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.

How can i input several integer or another types?

I want to enter several numbers for some operations. But i need to add this numbers without stopping. I mean, for example i wanna that program asks me how many integer i want to enter, after for example i yped 5 and click enter, it should give me opportunity to enter my 5 numbers (For example, 12, 34, 54, 23, 9) in the lines. Then i will use this numbers for something in my program.
i am using Scanner class for entering the number. But i wanna to enter several numbers in once input.
package frlr;
import java.util.Scanner;
public class Frlr {
public static void main(String[] args) {
System.out.println("Please enter your numbers: ");
Scanner in = new Scanner(System.in);
int myNumbers = in.nextInt();
System.out.println(myNumbers);
}
}
I need, when program asks me "Please enter your numbers:" if i enter 5 , it should be the count of the numbers which i will enter in the next steps.
You can use for loop, for loop allows you enter the amount of numbers you entered in your first scanner.
For example:
1) you scan the amount of number you want to enter
2) in for loop you use that number as an endpoint
so your for loop is gonna look like this:
for(initialization; condition(your condition is your scan) ; increment/decrement)
{
statement(s);
}
3) you statement is going to be another scan, or as you refer to it as entering several numbers
If you want to use the numbers later you can save them in an Array. First you ask the user how big the array has to be (quantity). Then you initialize an Array with the user input size. You need to watch out that the number is positive. After that you make a for loop, that has the input quantity times of iterations. After each step you save the number in the proper spot. In the end you can output the numbers.
Validation of user inputs can be done with Regular Expressions. Here is a good tutorial on RegEx: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
import java.util.Arrays;
import java.util.Scanner;
public class VariableInputs
{
private Scanner scanner;
private String input;
private boolean isInputBad;
public VariableInputs()
{
this.scanner = new Scanner(System.in);
this.isInputBad = false;
}
public void startInteraction()
{
System.out.println(
"How many Integers would you like to enter? Enter a positive number that is smaller than 100.");
int quantity;
do
{
if (isInputBad) System.out.println("Enter a valid number."); // this gets printed if the user entered a wrong input (f.e. "abc").
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d{1,2}")); // this checks if the input contains only number 0-9. The input has to have atleast 1 and max 2 numbers.
isInputBad = false;
quantity = Integer.parseInt(input); // because of the regular expression we know for sure that the input string is a number. So we can parse it.
int[] numbers = new int[quantity]; // init array with input quantity.
System.out.println("Good job my friend. You have entered " + quantity
+ ". Go ahead and enter those numbers.");
for (int i = 0; i < quantity; i++)
{
do
{
if (isInputBad) System.out.println("Enter a valid number.");
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d"));
numbers[i] = Integer.parseInt(input);
isInputBad = false;
}
System.out.println("Good job my friend. You have entered " + quantity
+ " numbers.");
System.out.println("The numbers are: " + Arrays.toString(numbers));
scanner.close();
}
public static void main(String[] args)
{
VariableInputs vi = new VariableInputs();
vi.startInteraction();
}
}
You can try this code and see if its useful:
import java.util.Scanner;
import java.util.Arrays;
public class ScannerIn {
public static void main(String[] args) {
System.out.print("Please enter how many numbers (between 1 and 10)? ");
Scanner in = new Scanner(System.in);
int numbersCount = in.nextInt();
System.out.println(numbersCount);
if (numbersCount <= 0 || numbersCount > 10) {
System.out.println("Numbers count must be between 1 and 10. Exit program!");
System.exit(0);
}
int [] myNumbers = new int [numbersCount];
for (int i = 0; i < numbersCount; i++) {
System.out.print("Please enter your number: ");
in = new Scanner(System.in);
myNumbers[i] = in.nextInt();
}
System.out.println("Numbers input: " + Arrays.toString(myNumbers));
}
}

java characters in a string

so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));

Java - Reading/Scanning a text file for string length and using it in the program

I am trying to make a simple game of hangman in Java. I do have a text file named dictionary.txt containing 120K words from the English dictionary. The problem arises when I am going to prompt the user for a word length and displaying number of words with that particular length.
After spending a fair amount of time here and googling I have gotten this far but now I am stuck:
import java.util.Scanner;
import java.io.*;
import java.io.IOException;
public class Hangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// read the dictionary file
File file = new File("dictionary.txt");
StringBuilder contents = new StringBuilder();
BufferedReader reader = null;
// prompt the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
}
}
My goal is to prompt the user for a word length and if the desired word length does not exist in the dictionary.txt file then it keeps asking until a valid response is given.
I would also like to be able to prints how many words have a given word length (e.g if user types in "10", then it displays how many words in dictionary.txt have the length of 10 letters.
The following part of the code is the one I hope to replace with code that reads the txt file and acts thereafter:
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
It is possible that I have taken the wrong approach, so all feedback is very welcome!
This code can be used to establish a count of words of each word length.
// map where the key is the length of a word and
// the value is the number of words of that length
Map<Integer, Integer> numberOfWordsOfLength = new HashMap<>();
Scanner dictionaryScanner = new Scanner(file);
while (dictionaryScanner.hasNext())
{
String word = dictionaryScanner.next();
int wordLength = word.length();
numberOfWordsOfLength.put(wordLength, 1 +
numberOfWordsOfLength.containsKey(wordLength) ?
numberOfWordsOfLength.get(wordLength) :
0);
}
Then, when you want to know if there are any words of a given length, you can use this.
numberOfWordsOfLength.containsKey(length)
When you want to get the number of words in the dictionay that have a given length, you can use this.
numberOfWordsOfLength.get(length)
Later, when you want to select a random word of a given length, you can do something like this.
int wordIndex = new Random().nextInt(numberOfWordsOfLength.get(length));
Scanner dictionaryScanner = new Scanner(file);
String word;
while (dictionaryScanner.hasNext())
{
String candidateWord = dictionaryScanner.next();
if (candidateWord.length() != length) continue;
if (wordIndex == 0)
{
word = candidateWord;
break;
}
--wordIndex;
}
Try this:
try
{
Scanner input = new Scanner(file);
boolean flag = true;
while(flag)
{
ArrayList<String> words = new ArrayList<String>(120000);
while(input.hasNextLine())
{
String s = in.nextLine();
if(s.length() == wordLength)
{
words.add(s);
}
}
if(words.isEmpty())
{
System.err.print("Invalid word length, please try again\n>");
wordLength = keyboard.nextInt();
}
else
{
flag = false;
System.out.println("There were " + words.size() + " such words");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
Does it work?

Categories

Resources