Hi, I am doing a computer home course and they have asked me to practise the use of the switch by creating an class which I then instantiate in another program to invoke the method that the switch is in. Phew.

Anyway, the book I am currently learning from is very vague as to how to do this, so I thought I'd ask here to find out where I am going wrong.

Here is my code:

public class Instructor
{
	public void congratulateStudent(char grade)
	{
		switch (grade)
		{
		case 'A':
			System.out.println("Excellent.");
			break;
		case 'B':
			System.out.println("Nice job.");
			break;
		case 'C':
			System.out.println("Not bad.");
			break;
		case 'D':
			System.out.println("Almost!");
			System.out.println("See you next semester.");
			break;
		case 'F':
			System.out.println("See you next semester.");
			break;
		default:
			System.out.println("Error! The Grade you entered is not valid.");
		}
	}
}

And the code that uses this object:

public class Grades
{
	public static void main(String[]args)
	{
		Instructor grades = new Instructor();
		grades.congratulateStudent();
		char grade = args[0].charAt(0);
	}
}

You might need to make a minor edit--

public class Grades
{
	public static void main(String[]args)
	{
		Instructor grades = new Instructor();
		grades.congratulateStudent( 'A' ); // enter a char as parameter here, 'A', 'B', 'C' etc
		char grade = args[0].charAt(0);
	}
}

Sorry, I should've added that the 'Grade' needs to be an command line argument rather than a part of the program.

Actually you need the argument as input in the method.

public class Grades
{
	public static void main(String[]args)
	{
		Instructor grades = new Instructor();
		
		char grade = args[0].charAt(0);

                grades.congratulateStudent( grade  ); 
               
	}
}

Of you will need to check if the user has given an argument:

if (args.length>0) {
                Instructor grades = new Instructor();
		
		char grade = args[0].charAt(0);

                grades.congratulateStudent( grade  ); 
} else {
    System.out.println("No argument given");
}

Actually you need the argument as input in the method.

public class Grades
{
	public static void main(String[]args)
	{
		Instructor grades = new Instructor();
		
		char grade = args[0].charAt(0);

                grades.congratulateStudent( grade  ); 
               
	}
}

Of you will need to check if the user has given an argument:

if (args.length>0) {
                Instructor grades = new Instructor();
		
		char grade = args[0].charAt(0);

                grades.congratulateStudent( grade  ); 
} else {
    System.out.println("No argument given");
}

That worked a treat, thank you.

This article has been dead for over six months. Start a new discussion instead.