patternjavaMinor
Program to find the element in an array
Viewed 0 times
thearrayprogramelementfind
Problem
I'd like this code to be improved.
import java.util.Scanner;
public class ArrayElementFind {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr= { "A","B","C","D"};
Scanner in=new Scanner(System.in);
System.out.println("Enter the char to search");
String a=in.nextLine();
//int len=arr.length;
boolean check=loopcheck(arr,a);
if(check){
System.out.println("Element is present");
}
else{
System.out.println("Element is not present");
}
}
private static boolean loopcheck(String[] arr, String a) {
// TODO Auto-generated method stub
for(String s:arr){
if(s.equals(a)){
return true;
}
}
return false;
}
}Solution
-
Since you're not using the
-
You should consider converting
I would also rename
The renaming also applies to
Since you're not using the
try-with-resources statement with Scanner, you must close it at the end of main() to avoid leaking resources:in.close();-
You should consider converting
a to uppercase, in case the input is in lowercase.I would also rename
a to something like guess. The name a says nothing about this variable, and it's generally discouraged to use single-letter variable names.String guess = in.nextLine().toUpperCase();The renaming also applies to
arr. You could name it something like elemsToCheck.Code Snippets
in.close();String guess = in.nextLine().toUpperCase();Context
StackExchange Code Review Q#56967, answer score: 6
Revisions (0)
No revisions yet.