I am trying to make some code that should keep track of a win/loss ratio. I have a for loop that checks if a name is present in a separate variable, this works but when I try to do it again it stalls.
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
After the code it should go back to a while loop, but it just stalls instead. If I comment out the name 2 part, the code works, but I need both parts.
Edit 1:
Heres the whole code
public class Counter {
#SuppressWarnings("resource")
public static void main(String[] args) {
int intTemp;
String stringTemp;
int keepGoing = 1;
int numPlayers = 0;
Player[] players = new Player[999];
Scanner scan = new Scanner(System.in);
System.out.println("Melee Score Tracker");
while (keepGoing == 1) {
System.out.println("\nPrint Scores\t1\nNew Match\t2\nNew Player\t3\nExit\t\t4");
intTemp = scan.nextInt();
// Print Scores
if (intTemp == 1) {
intTemp = 0;
System.out.print("\n");
for (int i = 0; i < numPlayers; i++) {
players[i].print();
}
}
// New Match
if (intTemp == 2) {
intTemp = 0;
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
}
// New Player
if (intTemp == 3) {
intTemp = 0;
System.out.println("\nWhat's the player's name?");
scan.nextLine();
stringTemp = scan.nextLine();
players[numPlayers] = new Player();
players[numPlayers].name = stringTemp;
numPlayers++;
System.out.println(numPlayers);
}
// Exit
if (intTemp == 4) {
System.exit(0);
}
}
}
}
It stalls because of this;
scan.nextLine();
scan.nextLine();
String name2 = scan.nextLine();
It is waiting for input 3 times. You only want input once so replace it with;
String name2 = scan.nextLine();
In the future things like this can easily be debugged by checking if the code actually enters the for loop by printing out a little message in the loop.
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
System.out.println("We have entered the loop.");
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
If you see output in the console then you know the problem is not with the loop itself, but is before it.
Related
import java.util.Arrays;
import java.util.Scanner;
public class Grocer2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] names = new String[5];
int count = 0;
while(true){
System.out.println("What is your name: ");
// Store scanner input in name
String name = scan.nextLine();
// Add name into array
names[count] = name;
count++;
if(count == 5){
break;
}
}
System.out.println(Arrays.toString(names));
while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
}else{
System.out.println("Not here");
}
}
break;
}
scan.close();
}
}
I am trying to add Scanner inputs into an array and I am trying to search for the element in an array using a for loop. The for loop looped through all the elements and print out "Not here" when names[i] is not equal to the Scanner input. How do I fix this issue ?
while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
bool isFound = false;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
isFound = true;
break;
}
}
if(!isFound){
System.out.println("Not here");
}
break;
}
If you want it to print not here only when you have not found the element at all you should put it after the for loop. So you would loop through the whole array if you find the name say that you found it and then if you didn't u can print not here so something like that :
while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
boolean isThere=false;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
isThere = true;
break;// break only if you want the first time the String appeared
}
}
if(!isThere){
System.out.println("Not here");
}
break;
}
Now that should work but here the while loop doesn't do anything. Consider removing it or doing something else with it since when you are doing the first loop you are breaking directly the first time so it's as if there were no loop at all.
You can create a boolean called contactFound and set it to true when a matching name has been found. You may also want to break out of the loop when this happens. Outside of the for loop, print "Not here" if contactFound is false, as shown below.
boolean contactFound = false;
for (int i = 0; i < names.length; i++) {
if (names[i].equals(contact)) {
System.out.println("They are in aisle " + i);
contactFound = true;
break; // If you want the loop to stop when a matching name has been found
}
}
if (!contactFound) System.out.println("Not here");
Your second while loop never loops. And you can use a do-while loop for the first loop. Here is a more compact version of the code:
Scanner scan = new Scanner(System.in);
String[] names = new String[5];
int count = 0;
do {
System.out.println("What is your name: ");
// Add name into array
names[count] = scan.nextLine();
count++;
} while (count != 5);
System.out.println(Arrays.toString(names));
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
int aisle = -1;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){aisle = i; break;}
}
if (aisle != -1) System.out.println("They are in aisle " + aisle);
else System.out.println("Not here");
scan.close();
Edit: Doing this is a lot easier with an ArrayList instead of dynamic arrays. Here is a version that uses ArrayLists:
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<>(5);
for (int i = 0; i<5; i++){
System.out.println("What is your name: ");
names.add(scan.nextLine());
}
System.out.println(names);
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
if (names.contains(contact)) System.out.println("They are in aisle " + names.indexOf(contact));
else System.out.println("Not here");
scan.close();
import java.util.Arrays;
import java.util.Scanner;
public class Grocer2 {
public static void main(String[] args) {
int count = 0;
int size = 5;
//you should check here
boolean check = false;
Scanner scan = new Scanner(System.in);
String[] names = new String[size];
for (int i = 0; i<size; i++) {
System.out.println("What is your name: ");
// Store scanner input in name
String name = scan.nextLine();
// Add name into array
names[count] = name;
count++;
if (count == size) {
break;
}
}
System.out.println(Arrays.toString(names));
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
for (int i = 0; i<names.length; i++) {
if (names[i].equals(contact)) {
System.out.println("They are in aisle " + i);
check = true;
break;
}
}
if (!check) {
System.out.println("Not here");
}
scan.close();
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm writing a Java program that creates a menu and lets the user pick an option. The while loop in my getValidChoice method is not functioning as it should. It is an infinite loop, please help! New to Java! Ask questions for clarity!
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main
{
public static String createMenu(String[] listOfChoices, String menuTitle) {
String bigStr = menuTitle + "\n\n";
int count = 1;
for (int i = 0; i < listOfChoices.length; i++) {
String littleStr = count + ". " + listOfChoices[i] + "\n";
count = count + 1;
bigStr = bigStr + littleStr;
}
return bigStr;
}
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = true;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
while (error == true || (Float.valueOf(number) > numChoices && Float.valueOf(number) < 1)) {
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
public static void main(String[] args) {
String[] employeeList = new String[50];
String[] chList = {"Add New Employee", "Delete Employee", "Change Employee Name", "Print Employee Roster", "Quit"};
String menuStr = createMenu(chList, "Main Menu");
int ch = getValidChoice(chList.length, menuStr);
System.out.println(ch);
}
}
Replace
for (int i = 0; i > number.length(); i++)
with
for (int i = 0; i < number.length(); i++)
Since your for loop counter (i.e. i) is increasing by 1 with each iteration, it will eventually become equal to number.length() and the loop will terminate if we put the condition as i < number.length(). In your code, the check fails for the first time itself.
Note that you need to make this change at two places, outside the while loop and also inside the while loop. Given below is the corrected code:
import java.util.Scanner;
public class Main {
public static String createMenu(String[] listOfChoices, String menuTitle) {
String bigStr = menuTitle + "\n\n";
int count = 1;
for (int i = 0; i < listOfChoices.length; i++) {
String littleStr = count + ". " + listOfChoices[i] + "\n";
count = count + 1;
bigStr = bigStr + littleStr;
}
return bigStr;
}
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = true;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
while (error == true || Float.valueOf(number) > numChoices || Float.valueOf(number) < 1) {
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
public static void main(String[] args) {
String[] chList = { "Add New Employee", "Delete Employee", "Change Employee Name", "Print Employee Roster",
"Quit" };
String menuStr = createMenu(chList, "Main Menu");
int ch = getValidChoice(chList.length, menuStr);
System.out.println(ch);
}
}
A sample run:
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: a
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: 6
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: -1
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: 3
3
This change in getValidChoice() will fix the problem. Start with boolean error = false; instead of boolean error = true;.
Starting of the changed method:
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = false; //THIS IS THE CHANGE
Scanner choice = new Scanner(System.in);
Edit: Added the changed method
The places where changes have been made are commented with "CHANGE".
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = false;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) { //CHANGE: '<' and not '>'
inputArray[i] = number.charAt(i);
if ( !Character.isDigit(inputArray[i])){ //CHANGE: Notice '!'
error = true; //CHANGE: Error: The character is not a digit.
}
}
while (error == true || Float.valueOf(number) > numChoices || Float.valueOf(number) < 1) {
error = false; //CHANGE: Reset error back to false.
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i > number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
I have a string input which, that input have a team name and score separated by one space. e.g bb 3 , teamd 5 the winner should be teamd
In order to get the winner team that scored highest score, i'm doing following:
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String str = "";
String winnerTeam = "";
int winnerScore = 0, countedChar = 0;
for (int i = 0; i < cases; i++) {
str += scanner.nextLine();
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
countedChar++;
if (arr[i] == ' ') {
if (str.charAt(i + 1) > winnerScore) {
winnerTeam = "";
winnerScore = (int) str.charAt((int) i + 1);
for (int j = 0; j < countedChar; j++) {
winnerTeam += str.charAt(j);
}
countedChar = 0;
} else {
//winnerTeam = "";
countedChar = 0;
}
}
}
System.out.println(winnerTeam);
}
But it's not work prefect, It's print wired result, how to make that work as expect ?
I haven't tried your code, But I would imagine a big problem is the concatenation of str += scanner.nextLine(); The new line is going to be appended straight onto the end of the previous lines number
Have a look at this
Scanner sc = new Scanner(System.in);
int bestScore = Integer.MIN_VALUE;
String team = "Nothing entered";
System.out.println("how many teams");
int count = sc.nextInt();
sc.nextLine();
while (count-- > 0) {
System.out.println("Entered team,score");
String line = sc.nextLine();
String arr [] = line.split(" ");
// check size - TBD
if (Integer.parseInt(arr[1]) > bestScore) {
bestScore = Integer.parseInt(arr[1]);
team = arr[0];
}
}
System.out.println("nest team is " + team + " with a score of " + bestScore);
If I have to do something like that I will do it like this:
import java.util.*;
public class winner {
public static void main (String args []) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String winnerTeam = "";
String Team="";
int winnerScore = 0, score = 0;
for (int i = 0; i < cases; i++) {
Team = scanner.next();
score = scanner.nextInt();
if(score > winnerScore){
winnerTeam = Team;
winnerScore = score;
}
}
System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore);
}
}
I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code
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);