So I'm trying to create a program that takes in the student's GPA and prints out if they are graduating at an honor's level, graduating, or not graduating. I have most of the code figured out, but I am trying to make it so that ALL of the input is first, and then it will go back and print out whether each student is graduating. But what I am getting is printing out the graduation status for each student immediately after the input for that student.
I'm getting this:
Enter the number of GPAs: 3
GPA #0: 3.99
Student #0: Summa Cum Laude
GPA #1: 3.1
Student #1: Graduating
GPA #2: 2
Student #2: Graduating
When I want this:
Enter the number of GPAs: 3
GPA #0: 3.99
GPA #1: 3.1
GPA #2: 2
Student #0: Summa Cum Laude
Student #1: Graduating
Student #2: Graduating
Here is my code:
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
int array[] = new int[size];
double gpa;
for (int i = 0; i < size; i++) {
System.out.print("GPA #"+ i + ": " );
gpa = sc.nextDouble();
if (gpa >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (gpa >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (gpa >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (gpa >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}}
First you need to fill the array with values GPA we declare an array of double
double array[] = new double[size];
We iterate through for loop and we ask user to enter GPA and we fill our array with those values
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
Now we have array with our values filled so what should we do know we print it by checking array values with our if statements.
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
FULL CODE
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
double array[] = new double[size];
double gpa;
int index = 0;
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
It sounds like you want to have one list of GPA's immediately followed by another list of status'. If that is the case, then you have 2 separate lists, which will require 2 separate loops.
Make a loop that prints out your GPA's, then after that loop finishes, have another loop that prints out the status'. Also, you will need some way to store those values from the first loop. Maybe an array?
Related
I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.
I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn
import java.util.Scanner;
public class QuestionTwo{
public static void main(String[] args) {
Integer number;
Character first, middle, last;
Scanner keyboard = new Scanner(System.in);
System.out.print("First name: ");
first = keyboard.next().charAt(0);
System.out.print("Middle name: ");
middle = keyboard.next().charAt(0);
System.out.print("Last name: ");
last = keyboard.next().charAt(0);
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
number = keyboard.nextInt();
if (number == 1) {
System.out.println("Sort order: 1");
if ((first) < (middle) && (first) < (last)) {
if ((middle) < (last)) {
System.out.println(first + middle + last);
}
if ((last) < (middle)) {
System.out.println(first + last + middle);
}
}
if ((middle) < (first) && (middle) < (last)) {
if ((first) < (last)) {
System.out.println(middle + first + last);
}
if ((last) < (first)) {
System.out.println(middle + last + first);
}
}
if ((last) < (middle) && (last) < (first)) {
if ((middle) < (first)) {
System.out.println(last + middle + first);
}
if ((first) < (middle)) {
System.out.println(last + first + middle);
}
}
}
if (number == 2) {
System.out.println("Sort order: 2");
if ((first) > (middle) && (first) > (last)) {
if ((middle) > (last)) {
System.out.println(first + middle + last);
}
if ((last) > (middle)) {
System.out.println(first + last + middle);
}
}
if ((middle) > (first) && (middle) > (last)) {
if ((first) > (last)) {
System.out.println(middle + first + last);
}
if ((last) > (first)) {
System.out.println(middle + last + first);
}
}
if ((last) > (middle) && (last) > (first)) {
if ((middle) > (first)) {
System.out.println(last + middle + first);
}
if ((first) > (middle)) {
System.out.println(last + first + middle);
}
}
}
}
}
The output that I get from this is a large integer value, whereas what the program should do is ask for a first name, then middle name, then last name. It should then ask for which sort order, 1 being ascending and 2 being descending. What this means is that once it gets the name it looks through the names and counts the number of letters per name. It will then give the answer as the name sorted in the order that the user selected.
For example:
if I tell it my name is David H. Anderson, and click 1 for ascending order, my result should be "H. David Anderson", as H. is 2 symbols, David is 5 and Anderson is 8.
What it currently does is all of the above except for giving me the last line int he format I want (I end up just getting a number).
I would change a few things to get you started.
Firstly, your input should probably be a String
Secondly, remove .charAt(0)
Then compare the String lengths before printing them.
Try this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main2 {
private static ArrayList<String> splitAndSortFullName(String fullName, int sortOrder) {
String[] names = fullName.split(" "); //Split names by space character.
//Create a list with only non-empty names:
ArrayList<String> namesList = new ArrayList();
for (int i=0; i<names.length; ++i)
if (!names[i].isEmpty())
namesList.add(names[i]);
switch (sortOrder) {
case 1: Collections.sort(namesList); break;
case 2: Collections.sort(namesList, (a, b) -> { return b.compareTo(a); }); break;
}
return namesList;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = keyboard.nextLine(); //Read the full name. For example "John D. Doe".
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
int number = keyboard.nextInt();
System.out.println(splitAndSortFullName(fullName, number));
//For use with many full names, just re-call the method splitAndSortFullName(...). For examples:
System.out.println("Full examples:");
System.out.println(splitAndSortFullName("John D. Doe", 1));
System.out.println(splitAndSortFullName("Alice K. Example", 2));
System.out.println(splitAndSortFullName("Martin T. Anderson", 1));
}
}
In this code, the user enters his complete name fully.
import java.util.Scanner;
public class QuestionTwo
{
public static void main(String[] args)
{
Integer number;
String first, middle, last;
Scanner keyboard = new Scanner (System.in);
System.out.print("First name: ");
first = keyboard.next();
System.out.print("Middle name: ");
middle = keyboard.next();
System.out.print("Last name: ");
last = keyboard.next();
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
number = keyboard.nextInt();
int firstLength = first.length();
int middleLength = middle.length();
int lastLength = last.length();
if(number == 1)
{
System.out.println("Sort order: 1");
if(firstLength < middleLength && firstLength < lastLength)
{
if(middleLength < lastLength)
{
System.out.println (first + " " + middle + " " + last);
}
if(lastLength < middleLength)
{
System.out.println (first + " " + last + " " + middle);
}
}
if(middleLength < firstLength && middleLength < lastLength)
{
if(firstLength < lastLength)
{
System.out.println (middle + " " + first + " " + last);
}
if(lastLength < firstLength)
{
System.out.println (middle + " " + last + " " + first);
}
}
if(lastLength < middleLength && lastLength < firstLength)
{
if(middleLength < firstLength)
{
System.out.println(last + " " + middle + " " + first);
}
if(firstLength < middleLength)
{
System.out.println(last + " " + first + " " + middle);
}
}
}
if(number == 2)
{
System.out.println("Sort order: 2");
if(firstLength > middleLength && firstLength > lastLength)
{
if(middleLength > lastLength)
{
System.out.println (first + " " + middle + " " + last);
}
if(lastLength > middleLength)
{
System.out.println (first + " " + last + " " + middle);
}
}
if(middleLength > firstLength && middleLength > lastLength)
{
if(firstLength > lastLength)
{
System.out.println (middle + " " + first + " " + last);
}
if(lastLength > firstLength)
{
System.out.println (middle + " " + last + " " + first);
}
}
if(lastLength > middleLength && lastLength > firstLength)
{
if(middleLength > firstLength)
{
System.out.println(last + " " + middle + " " + first);
}
if(firstLength > middleLength)
{
System.out.println(last + " " + first + " " + middle);
}
}
}
}
}
Listening to the comments and with help from thanopi57, I was able to get the proper answer. The first thing I did was to remove the ".AtChar(0)" and define the variables as Strings, not Characters. I then defined the variables as variable length, with variable xxxx becoming int xxxxLength=xxxx.Length();, doing this for all three variables (which converted them from String to Int). I then replaced the subsequent concatenation operands with my newly defined variables, I also added " " for spaces inbetween operands in the println lines.
case 2:
System.out.println("Please enter Book ID: ");
String userinput2 = sc.next();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
System.out.println("BookID: " + myBooks.get(i).getBookID() + "\nTitle: "
+ myBooks.get(i).getTitle() + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("Please enter new details of book");
System.out.println("Title: ");
String userinput7 = sc.next();
myBooks.get(i).setTitle(userinput7);
System.out.println("Author: ");
String u1 = sc.next();
myBooks.get(i).setAuthor(u1);
myBooks.get(i).setOnLoan(false);
myBooks.get(i).setNumLoans(0);
System.out.println("---------------------------------------------------");
System.out.println("The book has been successfully updated");
System.out.println("Book ID: " + myBooks.get(i).getBookID() + " " + "\nTitle: "
+ myBooks.get(i).getTitle() + " " + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("---------------------------------------------------");
}
else { System.out.println("Please enter a correct bookID");
}
}
I'm having a problem with my validation check. If the user enters a bookID that doesn't exist, instead of printing out "please enter a correct bookID" once, it prints it out 4 times, which amounts to the number of objects i have in the array list. Is there a way to sort this?
Your else statement is in the middle of the for statement
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
[[do stuff]]
}
else { System.out.println("Please enter a correct bookID");
}
}
It looks like it should be in the middle of the if statement
if (myBooks.get(i).getBookID().contains(userinput2)) {
for (int i=...) {
[[do stuff]]
}
}
else { System.out.println("Please enter a correct bookID");
}
I have a homework assignment and the program generates a random number of students taking a random number of tests. The user must enter the students names and test scores. Once that is done the program will print on the screen : STUDENT REPORT Scores for Fred:
Test #1: 78
Test #2: 80
Average for Fred: 79.0
Scores for Sue:
Test #1: 91
Test #2: 94
Average for Sue: 92.5
... and so on depending on what number of students and tests you get.
I get everything right up until the average part how can I fix it?
Here's my code:
public static void populateNames(String[] names)
{
for(int i = 0; i<names.length; i++)
{
out.print("Enter student " + (i+1) + " name: ");
names[i] = keyboard.next();
}
}
// Code your 3 methods below...
//Ask the user for the student name as well as the test scores
public static void populateTestScores(String[] names, int[][] scores)
{
out.println();
for(int i=0; i<names.length; i++)
{
out.println();
out.println("Entering scores for: " + names[i]);
for(int s=0; s<scores[0].length; s++)
{
out.print("Enter score for test #" + (s+1) + ": ");
scores[i][s] = keyboard.nextInt();
}
}
out.println();
}
//Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores)
{
out.println("STUDENT REPORT");
for(int i=0; i<names.length; i++)
{
out.print("Scores for " + names[i] + ": ");
out.println();
for(int s=0; s<scores[0].length; s++)
{
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
}
out.println();
int s=0;
if(s<scores[0].length)
{
s++;
double sum = 0;
sum += scores[i][s];
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}
The problem is in the way you're computing sum in printStudentReport: it only contains the second element in the list of scores because you're creating and adding to sum after the for loop (instead of creating before the loop and adding in it).
I'd rearrange that method to (reformatted for compactness):
// Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores) {
out.println("STUDENT REPORT");
for (int i = 0; i < names.length; i++) {
out.print("Scores for " + names[i] + ": ");
out.println();
double sum = 0;
for (int s = 0; s < scores[0].length; s++) {
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
sum += scores[i][s];
}
out.println();
if (0 < scores[0].length) {
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}