简体   繁体   English

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

[英]I need help updating an array in main from a method

This is the Main.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));

This is the BinarySearch.java class 这是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;
}

How do I use the addTopping method to add an topping into the q array in main without there being a String array parameter in the addTopping method? 我如何使用addTopping方法将topping添加到main中的q数组中,而在addTopping方法中没有String数组参数? Can I get help writing this method? 我可以在编写此方法方面获得帮助吗? Then How would i do printTopping() method? 那我该怎么做printTopping()方法呢?

This is the direction : 这是方向: 在此处输入图片说明

In main: 在主要方面:

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

In addTopping: 在addTopping中:

toppingStringArray[toppingStringArray.length - 1] = top;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM