I was asked to write a Java program which gets 5 strings from user and collects it in an array. Furthermore, I need to check every single string in the array and only print the ones who has more than four characters.
public static void main(String[] args) {
Scanner mbk = new Scanner(System.in);
int repetition[] = { 1, 2, 3, 4, 5 };
String words[] = new String[repetition.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + repetition[i] + ":");
words[i] = mbk.nextLine();
}
}
This is the code that I have written and I'm stuck. Can anyone help?
First of all, It's a very bad practice to use variable names like mbk
, the variable name should be easily understood by any other developer reading your code. It's name should reflect it's purpose. Here's a small revision of your code.
Also, Leaving a I/O stream open can cause you a big time of trouble, so i have also added the scanner.close
statement.
public static void main(String[] args) throws Exception {
Scanner userInput = new Scanner(System.in);
int maxArrayLength[] = { 1, 2, 3, 4, 5 };
String words[] = new String[maxArrayLength.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + maxArrayLength[i] + ":");
words[i] = userInput.nextLine();
}
for(int lengthCheckCounter = 0; lengthCheckCounter < words.length; lengthCheckCounter++)
if(words[lengthCheckCounter].length() > 4)
System.out.println(words[lengthCheckCounter] + "-" + words[lengthCheckCounter].length());
userInput.close();
}
Another way of closing the I/O stream/resources could be to use try-with-resources
block featured since JDK 1.7
. Then we can write your code as follows:
try(Scanner userInput = new Scanner(System.in)) {
// All other code
}
If you are on JDK 1.8
, you can use a single line to do everything as suggested in Lonely Neuron's comment:
// Initialize your words array here
// Take user input
// Print words greater than 4 using JDK 1.8 Filter below
Arrays.stream(words).filter(s -> s.length() > 4).forEach(System.out::println)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加