I'm new to Java and attempting this question where I'm supposed to input a pair of values (two strings one at a time) which is meant to loop until I've exited using ctrl z. Only the grade will be used for the switch; the name is just a dummy value.
My expected output will be:
Enter name: (Name is then entered)
Enter grade: (Grade is then entered)
Code repeats until EOC is hit.
What is the most effective way to implement a working loop using while (.hasNext())? The code I've tried to make is very flawed, as seen below.
public static void main(String[] args) {
int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
System.out.print("\nEnter name: ");
String nameInput = input.next();
System.out.print("Enter grade: ");
String gradeInput = input.next();
switch (gradeInput) {
case "A":
ACount++;
break;
case "B":
BCount++;
break;
case "C":
CCount++;
break;
case "D":
DCount++;
break;
}
}
System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);
}
I think this solution is what you are looking for, it switches between asking for the name and grade until you cancel it with ctrl + z. Personally I have been coding java for 4 years and never used a switch, so I just used simple if-else statements, also by using just print, not println, the phrase was getting into the var, which is the reason of me using println.
public static void main(String[] args) {
int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;
Scanner input = new Scanner(System.in);
boolean askingForName = false;
boolean first = true;
System.out.println("Enter name: ");
while(true) {
if (first) {
String nameInput = input.nextLine();
first = false;
continue;
}
if (askingForName) {
System.out.println("Enter name: ");
String nameInput = input.nextLine();
askingForName = false;
}else {
System.out.println("Enter grade: ");
String gradeInput = input.nextLine();
if (gradeInput.equalsIgnoreCase("A")) {
ACount++;
}else if (gradeInput.equalsIgnoreCase("B")) {
BCount++;
}else if (gradeInput.equalsIgnoreCase("C")) {
CCount++;
}else if (gradeInput.equalsIgnoreCase("D")) {
DCount++;
}
askingForName = true;
}
if (!input.hasNextLine())
break;
}
System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);
}
Related
I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}
i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
}
}
You should refactor to separate the loop for finding/not finding the ball (or not), and do whatever you need to do with the ball (or error if not found) OUTSIDE the loop. This helps with readability because more of your lines are less indented, and it helps communicate your intent because most of your code in the loop is only going to be executed once anyway.
int ballIndex = -1;
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
ballIndex = nameBallArray[i];
break;
}
}
if (ballIndex >= 0) {
// found - do everything using ballIndex
} else {
// not found - display error
}
Set a flag variable to 0 before loop. Inside if set it 1. After the loop check if it is still zero. then print appropriate message that no item found.
Boolean flag = false; // before loop
flag = true; //inside if
// After loop
if(!flag)
System.out.println("Not Found");
Try this:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
return;
}
}
System.out.println("ball not found");
}
You could create a boolean and set it to true in your if statement that means it's been found. You could check the boolean after loop to see if it's true or false then display error message if true.
Example:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
boolean found = false; //boolean for if it's found or not
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
found = true; //set boolean if found
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
break; //break out of loop if item found
}
}
//check if boolean is false then print error message
if (!found)
{
System.out.println("There was a problem finding your item.");
}
I also added a break at end of if statement to break out of the loop if the item was found(no point in continuing on if the item was already found).
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
I have four classes but they're just templates so I'll only post my main class (I have overridden toString for each). The sort method is at the bottom. Everything else is fine (more or less) with my code, but when I create the objects in the array and then go to sort them (by a string value called uid) sometimes one or two of them will be out of order. How can I fix this?
Here's the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
enum ClassStanding{FRESHMAN,SOPHOMORE,JUNIOR,SENIOR,UNKNOWN,MASTERS_STUDIES,PHD_STUDIES};
enum Major{CS,CEG,EE,ISE,BME,ME,MET,UNKNOWN};
enum StudentType{UNDERGRADUATE,GRADUATE,UNDECLARED};
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<>();
int counter;
boolean continueInput;
int contCounter;
do {
do {
System.out.print("Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: ");
switch (stdin.next().toLowerCase()) {
case "add":
add(stdin, studentList);
counter = 0;
break;
case "remove":
remove(studentList, stdin);
counter = 0;
break;
case "list":
list(studentList);
counter = 0;
break;
case "save":
String fileName = getFileName(stdin);
save(fileName, studentList);
counter = 0;
break;
case "sort":
counter = 0;
sort(studentList);
break;
default:
System.out.println("Improper input, please enter only ADD, REMOVE, LIST, or SAVE.");
counter = 1;
}
} while (counter == 1);
do {
System.out.print("\nDo you want to continue? Yes or no: ");
switch (stdin.next().toLowerCase()) {
case "yes":
contCounter = 0;
continueInput = true;
break;
case "no":
contCounter = 0;
continueInput = false;
break;
default:
contCounter = 1;
continueInput = false;
System.out.print("\nPlease only enter 'yes' or 'no'.");
}
} while (contCounter == 1);
} while (continueInput);
} // end main method
public static void add(Scanner stdin, ArrayList<Student> studentList) {
String firstName;
String lastName;
String uid;
StudentType studentType;
ClassStanding studentClassStanding;
Major major;
double overallGPA;
double majorGPA;
String majorProfessor;
boolean thesisOption;
System.out.print("Please enter the student's first name: ");
String tempName = stdin.next();
firstName = checkName(tempName);
System.out.print("Please enter the student's last name: ");
tempName = stdin.next();
lastName = checkName(tempName);
System.out.println("Please enter the student's UID in the format 'U####' or 'U#####': ");
String tempUID = stdin.next();
uid = checkUID(tempUID).toUpperCase();
int count;
do {
System.out.print("Please enter the student's status as UNDECLARED, UNDERGRADUATE, or GRADUATE: ");
switch (stdin.next().toUpperCase()) {
case "UNDECLARED":
studentType = StudentType.UNDECLARED;
studentClassStanding = setStudentClassStanding(studentType);
count = 0;
Student student = new Student(firstName, lastName,
uid, studentType, studentClassStanding);
studentList.add(student);
break;
case "UNDERGRADUATE":
studentType = StudentType.UNDERGRADUATE;
major = setMajor();
studentClassStanding = setStudentClassStanding(studentType);
System.out.println("Enter the student's overall GPA below.");
overallGPA = setGPA();
System.out.println("Enter the student's major GPA below.");
majorGPA = setGPA();
count = 0;
UnderGraduate underGraduate = new UnderGraduate(firstName, lastName, uid, studentType,
studentClassStanding, major, overallGPA, majorGPA);
studentList.add(underGraduate);
break;
case "GRADUATE":
studentType = StudentType.GRADUATE;
studentClassStanding = setStudentClassStanding(studentType);
majorProfessor = setMajorProfessor();
thesisOption = setThesisOption();
count = 0;
Graduate graduate = new Graduate(firstName, lastName, uid, studentType,
studentClassStanding, majorProfessor, thesisOption);
studentList.add(graduate);
break;
default:
System.out.println("Please enter either Undeclared, Undergraduate, or Graduate only.");
count = 1;
}
} while (count == 1);
} // end add method
public static String checkName(String tempName) {
int a = 1;
String name1;
Scanner scanner = new Scanner(System.in);
do {
name1 = tempName; // hold the value of firstName in name1
for (int i = 0; i < tempName.length(); i++) { // loop to check input consists of letters (is a name)
if (!Character.isLetter(tempName.charAt(i))) { // if non-letters detected, ensure this was intentional
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
tempName = scanner.nextLine();
if (tempName.equalsIgnoreCase("continue")) { // if user enters "continue", use original input
a = 0;
tempName = name1; // pass name1 value to firstName
break;
} else {
a = 1; // continue prompting for firstName
}
} else { // accept input
a = 0;
}
}
} while (a == 1); // loop to ensure proper input
return tempName;
} // end checkName method
public static String checkUID(String tempUID) {
Scanner scan = new Scanner(System.in);
int a;
do {
if (tempUID.charAt(0) == 'U' || tempUID.charAt(0) == 'u') {
if (tempUID.length() == 6 || tempUID.length() == 5) {
a = 0;
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} while (a == 1);
return tempUID;
} // end checkUID method
public static ClassStanding setStudentClassStanding(StudentType studentType) {
Scanner scan = new Scanner(System.in);
int count;
ClassStanding studentTempClassStanding = null;
do {
if (studentType == StudentType.UNDECLARED || studentType == StudentType.UNDERGRADUATE) {
System.out.print("Please enter the student's class standing as either Freshman, Sophomore, Junior, Senior, or Unknown: ");
switch (scan.next().toUpperCase()) {
case "FRESHMAN":
studentTempClassStanding = ClassStanding.FRESHMAN;
count = 0;
break;
case "SOPHOMORE":
studentTempClassStanding = ClassStanding.SOPHOMORE;
count = 0;
break;
case "JUNIOR":
studentTempClassStanding = ClassStanding.JUNIOR;
count = 0;
break;
case "SENIOR":
studentTempClassStanding = ClassStanding.SENIOR;
count = 0;
break;
case "UNKNOWN":
studentTempClassStanding = ClassStanding.UNKNOWN;
count = 0;
break;
default:
System.out.println("Please enter only Freshman, Sophomore, Junior, Senior, or Unknown.");
count = 1;
}
} else {
System.out.print("Please enter the student's class standing as either 'Masters' for Masters Studies or 'PhD' for PhD Studies: ");
switch (scan.next().toUpperCase()) {
case "MASTERS": studentTempClassStanding = ClassStanding.MASTERS_STUDIES; count = 0; break;
case "PHD": studentTempClassStanding = ClassStanding.PHD_STUDIES; count = 0; break;
default: System.out.println("Please enter only 'Masters' or 'PhD'.");
count = 1;
}
}
} while (count == 1);
return studentTempClassStanding;
} // end setStudentClassStanding method
public static Major setMajor() {
Major tempMaj = null;
Scanner s = new Scanner(System.in);
int c;
do {
System.out.print("Please enter the student's major as either CS, CEG, EE, ISE, BME, ME, MET, or Unknown: ");
switch (s.next().toUpperCase()) {
case "CS":
tempMaj = Major.CS;
c = 0;
break;
case "CEG":
tempMaj = Major.CEG;
c = 0;
break;
case "EE":
tempMaj = Major.EE;
c = 0;
break;
case "ISE":
tempMaj = Major.ISE;
c = 0;
break;
case "BME":
tempMaj = Major.BME;
c = 0;
break;
case "ME":
tempMaj = Major.ME;
c = 0;
break;
case "MET":
tempMaj = Major.MET;
c = 0;
break;
case "UNKOWN":
tempMaj = Major.UNKNOWN;
c = 0;
break;
default:
System.out.println("Please enter only the specified values. ");
c = 1;
}
} while (c == 1);
return tempMaj;
} // end setMajor method
public static double setGPA() {
Scanner s = new Scanner(System.in);
double gpa;
int a;
do {
try {
System.out.print("Please enter the student's GPA: ");
gpa = s.nextDouble();// read in the gpa
if (gpa < 0.0 || gpa > 4.0) { // ensure the gpa is in the correct range
System.out.println("Invalid input, please enter a positive value between 0.0 and 4.0.");
a = 1;
} else {
a = 0;
}
} catch (InputMismatchException ex) { //catch any exceptions, prompt for correct input
a = 1;
gpa = 0.0;
System.out.println("Sorry, please enter a double value.");
s.nextLine(); // skip the last input
}
} while (a == 1 || gpa < 0.0 || gpa > 4.0); //loop while gpa is negative or incorrect input is received
return gpa;
} // end setGPA method
private static String setMajorProfessor() {
Scanner s = new Scanner(System.in);
String prof;
System.out.print("Please enter the name of the major professor: ");
String tempName = s.nextLine();
prof = checkName(tempName);
return prof;
} // end setMajorProfessor method
private static boolean setThesisOption() {
Scanner s = new Scanner(System.in);
boolean thesis = false;
int a;
do {
System.out.print("Please enter 'yes' if a thesis will be written, otherwise enter 'no': ");
switch (s.next().toUpperCase()) {
case "YES": thesis = true; a = 0; break;
case "NO": thesis = false; a = 0; break;
default: System.out.println("Please enter only 'yes' or 'no'."); a = 1;
}
} while (a == 1);
return thesis;
} // end setThesisOption method
private static void list(ArrayList<Student> studentList) {
for (int i = 0; i < studentList.size(); i++) {
System.out.println(studentList.get(i).toString());
}
} // end list method
public static String getFileName(Scanner stdin) {
System.out.print("Please enter the file name: "); // Prompt for input
String fileString = stdin.next();
return fileString; // Pass the fileString var to the main method
}//end of getFileName method
private static void save(String fileName, ArrayList<Student> studentList) {
int a; // create a counter
Scanner stdin = new Scanner(System.in);
do {
try {
PrintWriter writer = new PrintWriter(fileName); // Create a printwriter
for (int i = 0; i < studentList.size(); i++) {
writer.print(studentList.get(i).toString() + "\n"); //Print the arraylist to file
}
writer.close(); //Close the printwriter and save the file
a = 0;
} catch (FileNotFoundException ex) { // Catch any exceptions
System.out.println("The file could not be found, please re-enter the file name: "); // get new file name if an exception is thrown
fileName = stdin.nextLine();
a = 1;
}
} while (a == 1); // loop while exceptions are thrown
System.out.println("All information has been saved at " + fileName); // output that the arraylist has been saved in the specified file
// Make the following its own method
System.out.print("Would you like to read the contents of the file? Yes or no: ");
int b;
do {
switch (stdin.next().toLowerCase()) {
case "yes": readFromFile(fileName); b = 0; break;
case "no": b = 0; break;
default: System.out.println("Please enter only yes or no."); b = 1;
}
} while (b == 1);
} // end save method
private static void remove(ArrayList<Student> studentList, Scanner stdin) {
System.out.print("Please enter the UID of the student to be removed: ");
String tempUID = stdin.next();
String uidRemove = checkUID(tempUID);
for (int i = 0; i < studentList.size(); i++) {
if ((studentList.get(i).getUid()).equalsIgnoreCase(uidRemove)) {
studentList.remove(i);
}
}
System.out.println("The student with UID " + uidRemove + " has been removed.");
} // end remove method
private static void sort(ArrayList<Student> studentList) {
String uidLessU1;
String uidLessU2;
for (int i = 0; i < studentList.size(); i++) {
uidLessU1 = (studentList.get(i).getUid()).substring(1, studentList.get(i).getUid().length());
for (int j = 0; j < studentList.size(); j++) {
uidLessU2 = (studentList.get(j).getUid()).substring(1, studentList.get(j).getUid().length());
if (Integer.parseInt(uidLessU1) < Integer.parseInt(uidLessU2)) {
Student hold = studentList.get(i);
studentList.set(i, studentList.get(j));
studentList.set(j, hold);
}
}
}
} // end sort method
private static void readFromFile(String fileName) {
System.out.println("The contents of " + fileName + " as read from NotePad: ");
try {
Scanner fileReader = new Scanner(new File(fileName)); //Create a scanner
while (fileReader.hasNextLine()) { //Loop to read the file
String fromFile = fileReader.nextLine();
System.out.println(fromFile); //Output the file contents
}
} catch (FileNotFoundException ex) { //Catch any exceptions
System.out.println("Exception caught");
}
} // end readFromFile method
} // end main class
A sample of the problem would be (at this point I've already entered all the values instantiating the objects):
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: sort //calls the sort method
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list // calls the list method and prints out the arraylist
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a //why is this out of place?
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Just make Student implement Comparable and then you can do
Collections.sort(studentList);