我需要从方法更新main中的数组的帮助

时间:2018-11-27 01:30:08

标签: java

这是Main.java

 Scanner input = new Scanner(System.in);
  String in="t";
  String [] t=new String[15];

  int c=0;
  int p=0;
  String n="p";
  for(int i=0;i<15;i++){
     System.out.print("Enter a topping (or type quit):");
     n=input.nextLine();

     if(n.equals("quit")){
        i=16;
        p=1;
     }else
        t[i]=n;
        c++;
     }

  String [] q=new String[c];

  if(t[c-1]==null){
   q=new String[c-1];
     for(int u=0;u<c-1;u++){
        q[u]=t[u];
     }
      Arrays.sort(q);
 if(p==0){
  System.out.println("No more toppings allowed."); 
 }
 for(int o=0;o<c-1;o++){
  System.out.println((o+1)+". "+q[o]);
 }

  }
  else{
   q=new String[c];
     for(int u=0;u<c;u++){
        q[u]=t[u];
     }
      Arrays.sort(q);
 if(p==0){
  System.out.println("No more toppings allowed."); 
 }

 for(int o=0;o<c;o++){
  System.out.println((o+1)+". "+q[o]);
 }

  }
  BinarySearch bs = new BinarySearch();
  System.out.println("\nWhat do you want to search for?");
  String search = input.nextLine();
  System.out.println("BinarySearch: "+bs.binarySearch(q, search));

这是BinarySearch.java类

public void printTopping() {

}
public boolean addTopping(String top) {
}

public int binarySearch(String[] words, String key) {
    int left = 0;
    int right = words.length - 1;
    int mid = 0;

        while (left <= right) {
        mid = (left + right) / 2;

        if ((words[mid] + "").trim().compareTo(key.trim()) < 0) {
            left = mid + 1;
        } else if ((words[mid] + "").trim().compareTo(key.trim()) > 0) {
            right = mid - 1;
        } else {
            return mid;
        }
    }
    return -1;
}

如何在addTopping方法中没有String数组参数的情况下,使用addTopping方法将topping添加到main中的q数组中?我可以在编写此方法方面获得帮助吗?那我该怎么做printTopping()方法呢?

这是方向:enter image description here

1 个答案:

答案 0 :(得分:0)

主要:

String[] toppingStringArray = Arrays.copyOf(q, q.length + 1);

在addTopping中:

toppingStringArray[toppingStringArray.length - 1] = top;