java - I want to search a specific element of an array and if it exists to return its index -
i have created array of type savings contains string (name) , double (account number). want search using account number , see if exist , return elements (name + account number) , index of array contain these elements. tried not work.
import java.util.arrays; import java.util.scanner; public class main { public static void main(string[] args){ savings[] arrayofsavings = new savings[5]; system.out.print("enter account number: "); scanner scan = new scanner(system.in); double ms = scan.nextdouble(); //loop until length of array for(int index = 0; index<= arrayofsavings.length;index++){ if(arrayofsavings[index].equals(ms)){ //print index of string on array system.out.println("found on index "+index); } } arrayofsavings[0] = new savings("giorgos",87654321); arrayofsavings[1] = new savings("panos",33667850); } }
/savings class/
public class savings extends generic {
public savings(string fn, double an) { super(fn, an); } @override public string tostring(){ return string.format("customer: %s \n acount number: %.1f, getfirstname(),getaccnumber(); }
}
you this, return -1 if doesn't exist, or index if you've found it. have make sure check case.
public static int findsavingsifexists(double accountnumber, savings[] allsavings) { for(int = 0; < allsavings.length(); i++) { if(allsavings[i].accountnumber == accountnumber) { return i; } } return -1; }
and use so
int index = findsavingsifexists(..., arrayofsavings); if(index != -1) { savings foundsavings = arrayofsavings[index]; } else { //not found }
Comments
Post a Comment