java programming help

sigh… any programmers want to help? i made this program, but works about 99%. the one thing i can’t figure out is how get spaces between the responses. for example, after entering the info for the course name, section, and id, the result could be something like “art132002” instead of “art 132 002.” it does the same thing for the student section too.

import java.util.Scanner;

public class gradeBook{

public static void main(String[] args) 
{
	Scanner keyboard = new Scanner(System.in);
	
	String courseName;
	int courseSection, courseNumber;
	
	System.out.println("Enter the course name");
	
	courseName = keyboard.next();
	
	System.out.println("Enter the course section");
	
	courseSection = keyboard.nextInt();
	
	System.out.println("Enter the course number");
	
	courseNumber = keyboard.nextInt();
	                          
	System.out.println("The course info is " + courseName + courseSection 
		+ courseNumber);
	
	System.out.println("Enter student names and press \"enter\" for the next name");
	
	String s1, s2, s3, s4, s5;
			
	s1 = keyboard.next();
	s2 = keyboard.next();
	s3 = keyboard.next();
	s4 = keyboard.next();
	s5 = keyboard.next();
		
	System.out.println("You have entered " + s1 + s2 + s3 +s4 + s5);
}

}

Java’s not my thing, but it’s worth pointing out that this reads much more nicely if you put it in a [noparse]




[/noparse] block. Here’s the pretty version:



import java.util.Scanner;

public class gradeBook{
	
	public static void main(String[] args) 
	{
		Scanner keyboard = new Scanner(System.in);
		
		String courseName;
		int courseSection, courseNumber;
		
		System.out.println("Enter the course name");
		
		courseName = keyboard.next();
		
		System.out.println("Enter the course section");
		
		courseSection = keyboard.nextInt();
		
		System.out.println("Enter the course number");
		
		courseNumber = keyboard.nextInt();
		                          
		System.out.println("The course info is " + courseName + courseSection 
			+ courseNumber);
		
		System.out.println("Enter student names and press \"enter\" for the next name");
		
		String s1, s2, s3, s4, s5;
				
		s1 = keyboard.next();
		s2 = keyboard.next();
		s3 = keyboard.next();
		s4 = keyboard.next();
		s5 = keyboard.next();
			
		System.out.println("You have entered " + s1 + s2 + s3 +s4 + s5);
	}
}


Welp, in C# I would say



"The course info is " + courseName + " " +  courseSection + " " + courseNumber
...
"You have entered " + s1 + " " + s2 + " " + s3 + " " + s4 + " " + s5


Does that work in Java?

That will work in Java.

Indeed, this is pretty much the answer. Simply amend the spaces as Strings between each entry.

Yeah, the canonical answer is just to add + " " + between all the string variables. Perhaps the more “general” solution would be to define a function that adds a delimiter between string tokens and returns the results, but making use of such a functions would:

  1. Be unnecessary (and less elegant and self explanatory) for such a simple program.
  2. Require either arrays/data types (messy for such a simple operation) or varargs (something most people don’t really even use in Java*).

The other solution is probably the more “C style” solution:

System.out.printf("The course info is %s %s %s
", courseName, courseSection, courseNumber);

Which may be more intuitive with the spacing requirements, but you have to explicitly state the newline, and I think most java programmers stick with println over printf anyway.

  • Ironically, I’m saying this in a context where the two functions I’m discussing unambiguously use varargs.

Good responses above. A more “robust” solution would be to strip any leading or trailing white space from the expected input, then add the spaces yourself (per suggestions above), so that you always end up with one, and only one, space in your final print out. If you don’t massage the user input you’ll end up with all kinds of junk output. Users… who needs em! (Plus it’s always a good idea to not trust user input. Who knows where it’s been?)

ok, that helped. however, i’m now puzzled by the if and else statements.
so if i decided to give an option of selectively putting information, this makes the program a little more interesting. basically, the program will compile in this format because theoretically there are no errors. However, the problem is that in terms of choices, i’m allowed to input only the course information. it will not allow me to either exit the program or allow me to put in student names. for some reason, after the first “if”, the program will refuse to recognize “else” because it says that it’s missing an “if” statement. what the hell?


import java.util.Scanner;

public class gradeBook2{
	
	public static void main(String[] args) 
	{
		Scanner keyboard = new Scanner(System.in);
		
		String courseName;
		String s1, s2, s3, s4, s5;
		int courseSection, courseNumber;
		{
			System.out.println("Enter \'c\' to input course info, \'n\' for student, \'q\' to exit");
			String response = keyboard.next();
			
			if (response.equalsIgnoreCase("c"))
			System.out.println("Enter the course name");
			courseName = keyboard.next();
			System.out.println("Enter the course section");
			courseSection = keyboard.nextInt();
			System.out.println("Enter the course number");
			courseNumber = keyboard.nextInt();                   
		    System.out.println("The course info is " + courseName + " " + courseSection + " "
			+ courseNumber);
			System.exit(0);
			
				 if (response.equalsIgnoreCase("n"))
				System.out.println("Enter student 1 name and press \"enter\" for the next name");
				s1 = keyboard.next();
				System.out.println("Enter student 2 name");
				s2 = keyboard.next();                                                                                                                                          
				System.out.println("Enter student 3 name");
				s3 = keyboard.next();
				System.out.println("Enter student 4 name");
				s4 = keyboard.next();
				System.out.println("Enter student 5 name");
				s5 = keyboard.next();
				System.out.println("You have entered
 ");
				System.out.println(s1);
				System.out.println(s2);
				System.out.println(s3);
				System.out.println(s4);
				System.out.println(s5);
				System.exit(0);
				
					 if (response.equalsIgnoreCase("q"))
					System.out.println("Goodbye");
					System.exit(0);
		}
	}
}

By first “if” do you mean “if (response.equalsIgnoreCase(“c”))”

That line doesn’t have a squiggly bracket. “{”, so it’ll only apply to the very next line.
To do multi-line statements you need use { } to contain the stuff after the if and else.

For what it’s worth I enforce a standard where brackets are always used, even for 1 line statements. (I’m a lead programmer for my real job.)

Like Mobius said, always use brackets when using if statements. Yes, you don’t have to for one line but if enhances readability and makes sure things like your current error don’t happen.

Also, I would suggest that you use try-catch blocks around the course section and course number code. Just because you’re looking for an Int doesn’t mean that the user will give you one. If they don’t then an exception will be thrown. If you don’t want to write the code to get them to enter it again then it should at least fail gracefully with a message rather than a stack trace

this part has been bugging me for hours. theoretically, i shouldn’t be having a compiling error, but the program keeps on coming back saying that the variable “grade” is not initialized, so the program will not print out the grade when i enter the score. that seems to be the only problem. but i thought i already initialized the variable “grade” by defining the limits for an ‘A’ grade, a ‘B’ grade etc…

any comments?



import java.util.Scanner;

public class gradeBook3{
	
	public static void main(String[] args) 
	{
		Scanner keyboard = new Scanner(System.in);
		
		char grade;
		String courseName;
		String s1, s2, s3, s4, s5;
		int courseSection, courseNumber;
		int score;
		{
			System.out.println("Enter \'c\' to input course info, \'n\' for student, \'g\' for grades, \'q\' to exit, ");
			String response = keyboard.next();
			
			if (response.equalsIgnoreCase("c")) {
				System.out.println("Enter the course name");
				courseName = keyboard.next();
				System.out.println("Enter the course section");
				courseSection = keyboard.nextInt();
				System.out.println("Enter the course number");
				courseNumber = keyboard.nextInt();                   
				System.out.println("The course info is " + courseName + " " + courseSection + " "
					+ courseNumber);
				System.exit(0);
			}
			else if (response.equalsIgnoreCase("n")) {
				System.out.println("Enter student 1 name and press \"enter\" for the next name");
				s1 = keyboard.next();
				System.out.println("Enter student 2 name");
				s2 = keyboard.next();                                                                                                                                          
				System.out.println("Enter student 3 name");
				s3 = keyboard.next();
				System.out.println("Enter student 4 name");
				s4 = keyboard.next();
				System.out.println("Enter student 5 name");
				s5 = keyboard.next();
				System.out.println("You have entered
 ");
				System.out.println(s1);
				System.out.println(s2);
				System.out.println(s3);
				System.out.println(s4);
				System.out.println(s5);
				System.exit(0);
			}
			else if (response.equalsIgnoreCase("g")) {
				System.out.println("enter the score");
				score = keyboard.nextInt();
				
				switch (score)
				{
				case 1:
					if (score >= 90)
						grade = 'A';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 2:
					if (score >= 80)
						grade = 'B';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 3:
					if (score >= 70)
						grade = 'C';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 4:
					if (score >= 60)
						grade = 'D';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				default:
					if (score < 60)
						grade = 'F';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				}
			}
			else if (response.equalsIgnoreCase("q")) {
					System.out.println("Goodbye");
					System.exit(0);
			}
		}
	}
}


I don’t know if it will fix your problem, but you are using switch incorrectly with the grades. All students will get Fs except those who get 1% - 4%. The number after the word “case” is the value of the variable you used to start the switch (i.e. score).

With ranges, you shouldn’t be using a switch at all. Just use the if statements by themselves. And save the output commands to go after the if statement (and only use one).

Oh, and initializing would be what you did at the top by writing “char grade;”

Changing the switch to if/thens/else ifs should work. I copied and pasted it, made the replacements and it compiled and ran fine. Well, fine except that you really want to employ type checking, as per geneb’s suggestion. I managed to have the program throw an exception on me the second or third time I ran it while trying out the different menu options, and I didn’t realize only ints were expected for some input values.

Isn’t that the definition, but not necessarily the initialization? I don’t program in Java, but for initialization, wouldn’t you need something like
char grade(‘F’);
Or does Java have a default initialization for chars?

Java doesn’t initialize anything by default. It is throwing the error that it may not have been initialized because it may not have by the time it is printed. To initialize the variable you have to assign it some value and all of your assignments are within if statements so it is possible that it will never receive a value before you use it.

To solve the issue, it is as simple as creating the variable like so: char grade = ‘A’;

To avoid inadvertent errors, I’d recommending initializing to something other than a valid grade. That way if your logic fails the students won’t all be acing the course (or failing if you default to an ‘F’). Initializing to something like ‘Z’ should catch your attention and let you know that something is falling through the cracks.

Here’s the problem with what you did initially for the grade error (with a minimal example):



char grade;
int score = scanner.nextInt();
if (score >= 90){
	grade = 'A'; 
}
System.out.println(grade);


Here’s a reduced example of the same

The problem is that what you’re doing is saying this:

“If the score is over 90, set grade to ‘A’, regardless, print out grade.” The compiler realizes that there’s a chance that score < 90 is a possibility*, grade will remain unset and be unable to be printed. This is bad.

Also, as others mentioned, switch (k) matches the values of k with the value in the case statement (only works for chars and ints!) so

switch (k) {
case 1:
}

Will match the case where “k == 1”. It’s… possible to do greater than statements and whatnot with switch, but it’d so messy it’s not worth considering. If you have a bunch of literals that needs evaluating, then use switch. Though honestly, there’s no real reason to use switch if you’re going to have breaks every block, it’s not even that much cleaner looking than big else if blocks. The real use of switches in Java is that code “falls through” without a break, making it cleaner looking if you want to write code that basically says “for this symbol, do this, but also all the stuff for these other symbols.”

  • Even if you, the programmer, can enforce all valid inputs (say, a unique if for every case), without an explicit else or default block it will complain since the compiler can’t be sure you’ve enforced all possible cases.

ah ok. well i understood the previous problem. i did fix it for the switch statement. probably not the best solution, but it works. new problem is that the while loop is not working for me. is it because of positioning? as is, the code below compiles, but it doesn’t recognize the coding for the while loop.



import java.util.Scanner;

public class gradeBook4{
	
	public static void main(String[] args) 
	{
		Scanner keyboard = new Scanner(System.in);
		
		char grade;
		String courseName;
		String s1, s2, s3, s4, s5;
		int courseSection, courseNumber;
		int score;
		boolean exit = false;
		do
		{
			System.out.println("Enter \'c\' to input course info, \'n\' for student, \'g\' for grades, \'q\' to exit, ");
			String response = keyboard.next();
			
			if (response.equalsIgnoreCase("c")) {
				System.out.println("Enter the course name");
				courseName = keyboard.next();
				System.out.println("Enter the course section");
				courseSection = keyboard.nextInt();
				System.out.println("Enter the course number");
				courseNumber = keyboard.nextInt();                   
				System.out.println("The course info is " + courseName + " " + courseSection + " "
					+ courseNumber);
				System.exit(0);
			}
			else if (response.equalsIgnoreCase("n")) {
				System.out.println("Enter student 1 name and press \"enter\" for the next name");
				s1 = keyboard.next();
				System.out.println("Enter student 2 name");
				s2 = keyboard.next();                                                                                                                                          
				System.out.println("Enter student 3 name");
				s3 = keyboard.next();
				System.out.println("Enter student 4 name");
				s4 = keyboard.next();
				System.out.println("Enter student 5 name");
				s5 = keyboard.next();
				System.out.println("You have entered
 ");
				System.out.println(s1);
				System.out.println(s2);
				System.out.println(s3);
				System.out.println(s4);
				System.out.println(s5);
				System.exit(0);
			}
			else if (response.equalsIgnoreCase("g")) {
				System.out.println("enter the score");
				score = keyboard.nextInt();
				
				switch (score)
				{
				case 100:
				case 99:
				case 98:
				case 97:
				case 96:
				case 95:
				case 94:
				case 93:
				case 92:
				case 91:
				case 90:
					grade = 'A';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
				break;
				case 89:
				case 88: 
				case 87:
				case 86:
				case 85:
				case 84:
				case 83:
				case 82:
				case 81:
				case 80:
					grade = 'B';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 79:
				case 78:
				case 77:
				case 76:
				case 75:
				case 74:
				case 73:
				case 72:
				case 71:
				case 70:
					grade = 'C';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 69:
				case 68:
				case 67:
				case 66:
				case 65:
				case 64:
				case 63:
				case 62:
				case 61:
				case 60:
					grade = 'D';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				case 59:
				case 58:
				case 57:
				case 56:
				case 55:
				case 54:
				case 53:
				case 52:
				case 51:
				case 50:
				case 49:
				case 48:
				case 47:
				case 46:
				case 45:
				case 44:
				case 43:
				case 42:
				case 41:
				case 40:
				case 39:
				case 38:
				case 37:
				case 36:
				case 35:
				case 34:
				case 33:
				case 32:
				case 31:
				case 30:
				case 29:
				case 28:
				case 27:
				case 26:
				case 25:
				case 24:
				case 23:
				case 22:
				case 21:
				case 20:
				case 19:
				case 18:
				case 17:
				case 16:
				case 15:
				case 14:
				case 13:
				case 12:
				case 11:
				case 10:
				case 9:
				case 8:
				case 7:
				case 6:
				case 5:
				case 4:
				case 3:
				case 2:
				case 1:
				case 0:
					grade = 'F';
					System.out.println("score = " + score);
					System.out.println("grade = " + grade);
					break;
				default:
					System.out.println("You have entered a non-valid score.");
					break;
				}
			}
			else if (response.equalsIgnoreCase("q")) {
					System.out.println("Goodbye");
					System.exit(0);
			}
		} while (exit); {
			System.out.println("Enter more data? Enter \'y\' for yes, \'e\' to exit.");
			String answer = keyboard.next();
			if (answer.equalsIgnoreCase("e"));
				exit = true;
		}
	}
} 



There are three issues with the loop:

  1. System.exit supersedes the loop. Once it hits that line, the program will exit. Remove them.
  2. You need to include the “Would you like to enter more data” question in the loop or else it will never be asked.
  3. Set the variable “exit” to true and if the user answers “no” to entering more data, then set it to false so that the program will break out of the loop.

The way a do-while loop works is as follows:

  1. Perform action within the loop.
  2. Test against the while statement.
  3. If the statement evaluates to true, go back to #1 in this list. If the statement evaluates to false, break out of the loop.

I don’t mean to be rude, but the issues you are having are very basic problems and should be some of the first things you are looking for. I suggest that you read the relevant chapters in your book and ask your professor to explain these concepts to you a bit better.

I’m not Java expert (I stick with C# mostly), but the first time I’m executing new code, especially code with a lot of flow control (if(), while(), switch()) is to run it in the debugger, so I can see exactly what the computer is doing line-by-line.

I highly highly highly recommend learning how to use the debugger. It’s not nearly as complicated as it looks (assuming you’re using a modern, competent IDE), and it will save you hours and hours later on-- if your programming class is anything like mine, it completely ignores the debugger. This is bad. IMO, you should step through programs in the debugger before attempting to write your own program.

Anyway, just my $0.02.