Skip to content

Instantly share code, notes, and snippets.

@DanCoughlin
Created October 31, 2019 23:19
Show Gist options
  • Save DanCoughlin/68260104b0547de697f383ad15b642ac to your computer and use it in GitHub Desktop.
Save DanCoughlin/68260104b0547de697f383ad15b642ac to your computer and use it in GitHub Desktop.
Answer to question 8 in quiz #module5
/*
8. Write a Java code snippet to ask a user how many classes they are taking this semester.
Create an array of courses to based on that input, and then ask the user
to enter each course and and put those in the courses array. When the user has
completed entering their courses, print out the list of courses under the
heading "----Sprint 2019 Course Schedule------". Final output should be something like:
----Sprint 2019 Course Schedule------
IST140
MATH110
ENG015
PSYCH002
(5 points)
*/
// Step 1 - Ask a user how many classes they are taking
System.out.println("How many classes are you taking this semester?");
// set up a scanner variable to get user input
Scanner s = new Scanner(System.in);
// User should respond with a number, so store this answer in an int variable
int numClasses = s.nextInt();
// Step 2 - Create an array of courses
// create the array with a number to indicate how many elements will be
// use the number of courses from the users answer above 'numClasses'
String[] courses = new String[numClasses];
// Step 3 - The user indicated above, the number of classes they are
// taking and we stored that number in 'numClasses'.
// We need to get all the courses from the user, so if we are doing
// the same thing many times in a row (in this case getting user input
// on their courses), we do this in a loop
/*System.out.println("What are the courses?");
for (int i=0; i < numClasses; i++) {
String c = s.next();
}*/
System.out.println("What are the courses?");
for (int i=0; i < numClasses; i++) {
String c = s.next();
// add each course provided by the user to the courses array
// created in step 2
courses[i] = c;
}
// Step 4 - display courses that we stored in our array. To display
// the contents of an array, used an enhanced loop
System.out.println("---- SPRING SCHEDULE ----");
for (String myCourse : courses) {
System.out.println(myCourse);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment