Reputation: 29
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);
}
Upvotes: 3
Views: 91
Reputation: 140
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);
}
Upvotes: 2