An array of 10 ready words is set. We enter any from the keyboard: if it matches a word from the array, we display "The word matches the string ...", if it does not match - "Error". My program works, but I want to improve it. Is it possible instead of the answer in the form of an array "Error Error ... The word matches the string ... Error" to display one answer? For example, if there is at least one match, it simply writes "The word matches the string ...", if not - "Error".

import java.util.Scanner; public class grammar { public static void main (String [] args){ String[] s = {"лист","буква","книга","стол","стул","нога","рука","нить","тонна","нос"}; Scanner in = new Scanner(System.in); for (int i=0; i<s.length; i++){ System.out.println(s[i]); } System.out.println(); System.out.println("Введите слово: "); String name = in.nextLine(); for (int i=0; i<s.length; i++) { if (s[i].equalsIgnoreCase(name)) { System.out.println("Слово совпадает со строкой '"+s[i]+"'"); } else { System.out.println("Ошибка"); } } } } 
  • If a match is found, display the message and exit the program. And the conclusion of the message that there is no match, do after the completion of the cycle. - Akina

2 answers 2

If the word is found, there is no need to go further in the cycle.

 import java.util.Scanner; class grammar { public static void main (String [] args){ String[] s = {"лист","буква","книга","стол","стул","нога","рука","нить","тонна","нос"}; Scanner in = new Scanner(System.in); for (int i=0; i<s.length; i++){ System.out.println(s[i]); } System.out.println(); System.out.println("Введите слово: "); String name = in.nextLine(); boolean inThisArray = false; String word = ""; for (int i=0; i<s.length; i++) { if (s[i].equalsIgnoreCase(name)) { inThisArray = true; word = s[i]; break; } } if (inThisArray) System.out.println("Слово совпадает со строкой " + word); else System.out.println("Ошибка"); } } 
  • Thank. Yes, I thought to use boolean, but did not know how. - Nikolay

If I understand you correctly, then one of the approaches may look as follows

 int i = 0; while ( i < s.length && !s[i].equalsIgnoreCase(name) ) i++; if ( i != s.length ) { System.out.println("Слово совпадает со строкой '"+s[i]+"'"); } else { System.out.println("Ошибка"); }