Shema Martin
Shema Martin

Reputation: 51

Can I change what a method returns into a variable?

I am writing a program that will get 5 different test codes, drop the lowest grade, and give the average of the highest 4. Is there a way when I call a method and rename what it returns?

import java.util.Scanner;
public class Num {
    public static void getScore(){

        Scanner score = new Scanner(System.in);
        boolean testNum = false;
        int grade = 0;
        do{
            try{
                testNum = true;
                System.out.print("Enter in a test grade.");
                grade = score.nextInt();

                if((grade < 0) || (grade > 100)){
                    System.out.print("Invalid Entry. ");
                    testNum = false;
                }
            }catch (Exception e){
                System.out.print("What you entered was not a grade. Try again. ");
                testNum = false;
                @SuppressWarnings("unused")
                String clear = score.nextLine();
            }
        }while(!testNum);


    }
}

Upvotes: 0

Views: 57

Answers (1)

Jordi Castilla
Jordi Castilla

Reputation: 27003

Is there a way when I call a method and rename what it returns?

Yes you can.

This method does not accept any variable and does not return any value:

public static void getScore(){

This accepts an int[] array (to store 5 codes) and returns and int.

public static int getScore(int[] codes){

To call it in the main:

public static void main(String[] args) {
    int[] codes = {5,6,7,8,9};
    int grade = Num.getScore(codes);
}

After I get grade to return can I change that to a different variable?

int otherGrade = grade;

To understand better method signatures: check JSL §8.4, when you declare a method:

MethodDeclaration:
    MethodHeader MethodBody

MethodHeader:
     MethodModifiersopt TypeParametersopt Result MethodDeclarator Throwsopt

MethodDeclarator:
    Identifier ( FormalParameterListopt )

  public static int getScore(int number) throws Exception;
//|      |      |   |        |           └ throwing an exception (Throwsopt)
//|      |      |   |        └──────────── receiving one int argument (MethodDeclarator FormalParameterListopt )
//|      |      |   └───────────────────── name hellow (MethodDeclarator Identifier)
//|      |      └───────────────────────── returning an int (Result)
//|      └──────────────────────────────── declared static (no class instance needed)
//└─────────────────────────────────────── is a public method (MethodModifiersopt)

Upvotes: 1

Related Questions