Search code examples
javaarraysvoid

I'm Getting The Error: 'void' type not allowed here


public static void displayMenu(String[] name, double[] price) {
 int i = 0;
 double pr = 0;
 System.out.println("Welcome to our store, we have the following. Please enter what you would like: ");
 for (int j = 0; j < name.length; j++) {
      pr = price[j];
      System.out.println((j + 1) + " - for " + name[j] + " (" + pr + ")");
 }
 System.out.println("0 - for checkout");
}

capitalize(name) is a void method that takes an array of strings as a parameter.

public static void capitalize(String[] name) {
  String s = "";
  for (int i = 0; i < name.length; i++) {
     s = name[i];
     s = s.substring(0,1).toUpperCase() + s.substring(1).toLowerCase();
     System.out.println(s);
  }                    
}

I wanted to use the "upper/lower cased" version of the String array but it gives an error:

error: 'void' type not allowed here
     System.out.println((j + 1) + " - for " + capitalize(name) + " (" + pr + ")");
                                                        ^

What can i do about this? *NOTE = It has to be done with a void method.


Solution

  • My original answer was indeed wrong. If you need to return void, instead of printing it, replace in the array (or create a new array with capitalized Strings):

    public void capitalize(String[] name) {
      String s = "";
      for (int i = 0; i < name.length; i++) {
         s = name[i];
         s = s.substring(0,1).toUpperCase() + s.substring(1).toLowerCase();
         name[i] = s;
      }                    
    }
    

    Then, in your print statement, print out name[j] (or whatever you called the new array, if you want to preserve original).