我想将“i”从最后一个方法返回到main方法作为索引。我无法弄清楚如何归还“i”,因为它包含在if语句中。 代码应该能够告诉用户名称在数组中的位置。
import java.util.*;
import java.io.*;
/**
* A simple array activity where the user will provide data for an array
that will be stored into an array. It will allow the user to search
any name in the array.
Katelynn Schoenrock
Ken Nguyen
Computer Science 1301
Activity 2
11/29/2016
*/
public class Array{
private static Student[] data = new Student[10];
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i< data.length; i++){
System.out.println("Enter Student name");
String name = keyboard.nextLine();
System.out.println("Enter Birthdate");
String birthDate = keyboard.nextLine();
System.out.println("Enter Address");
String address = keyboard.nextLine();
new Student(name, birthDate, address);
data[i] = new Student(name, birthDate, address);
}
String nameToLookFor = create();
int Index = Search(nameToLookFor);
System.out.println("Object's Index: " + Index);
}
/**
* This method obtains the user's input and returns the Student object
* @param return nameToLookFor
*/
public static String create(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name to search");
String nameToLookFor = keyboard.nextLine();
return nameToLookFor;
}
/**
* This method allows for the user to search any given name.
* @param return The index of the object
*/
public static int Search(String nameToLookFor){
for(int i = data.length - 1; i >= 0; i--){
if(data[i].getName().equalsIgnoreCase(nameToLookFor) ){
System.out.println(data[i]);
}
}
}
}
答案 0 :(得分:0)
只需从Search()
方法返回索引:
public static int Search(String nameToLookFor) {
int NOT_FOUND = -1;
for (int i=data.length - 1; i >= 0; i--) {
if (data[i].getName().equalsIgnoreCase(nameToLookFor) ) {
System.out.println(data[i]);
return i;
}
}
return NOT_FOUND;
}
如果找不到名称,我将返回-1
的值。这应该没问题,因为Java中的字符串不能有负索引。
答案 1 :(得分:0)
您需要将变量置于循环外部,并在找到值
时中断 public static int Search(String nameToLookFor){
int i = -1; // not found value
for(i = data.length - 1; i >= 0; i--){
if(data[i].getName().equalsIgnoreCase(nameToLookFor) ){
System.out.println(data[i]);
break;
}
return i;
}