I have a program that asks the user for a certain number of inputs (words) and asks for said inputs before appending them to an array. It is then supposed to sort through them and find the word of the smallest length. However, by the time I enter what should be the second to the last input, the program breaks and displays a "0".
There are two methods being used.
Main:
public static void main(String[] args) {
//Take user input to start program
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of words you'll input:");
int inputInt = sc.nextInt(); //The size of the array
//Set and initialize array
String[] wordsArray = new String[inputInt];
//Ask for input and append them to array
System.out.println("Please input the words of your choice:");
for (int i = 0; i < inputInt; i++) {
wordsArray[i] = sc.nextLine();
}//End of for loop
//Call method
System.out.println(minWordLength(wordsArray));
sc.close();
}//End of main
The method called:
public static int minWordLength(String arr[]) {
String smallestWord = arr[0];
for (int i = 1 ; i < arr.length ; i++) {
if (arr[i].length() < smallestWord.length()) {
smallestWord = arr[i];
}// End of conditional
}// End of for loop
return smallestWord.length();
}//End of minWordLength
What's wrong?
The problem comes after reading the input from your scan.nextInt() method of Scanner class, the cursor remains on the same line. so your enter is taken as input when you use nextLine() for first word in the array and that is why it gives 0 as output. . [https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo]
To resolve this, what you can do is that after taking your integer input, consume the left over line by using the nextLine(), then your code works fine as expected, Here is the rectified code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Take user input to start program
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of words you'll input:");
int inputInt = sc.nextInt(); // The size of the array
sc.nextLine();
// Set and initialize array
String[] wordsArray = new String[inputInt];
// Ask for input and append them to array
System.out.println("Please input the words of your choice:");
for (int i = 0; i < inputInt; i++) {
wordsArray[i] = sc.nextLine();
} // End of for loop
// Call method
System.out.println(minWordLength(wordsArray));
sc.close();
}
public static int minWordLength(String arr[]) {
String smallestWord = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() < smallestWord.length()) {
smallestWord = arr[i];
} // End of conditional
} // End of for loop
return smallestWord.length();
}// End of minWordLength2
}
which gives the output :
Please enter the amount of words you'll input:
2
Please input the words of your choice:
abde
as
2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments