Initialize An Array of Ints with Variables - java

I want to make an array of integer values that represent counters so I initialized it like this in my main method:
int [] counters = new int [7];
counters [countListAll] = 0;
counters [countEmployeeReport] = 0;
counters [countDivisionReport] = ;
counters [countSalaryReport] = 0;
counters [countRetirementReport] = 0;
counters [countMain] = 0;
counters [countOthers] = 0;
And now I have to pass this array to my menu() method so that I can increment each counter each time any of the options is chosen.
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [countListAll] ++;
break;
case 'E':
case 'e':
employeeReport();
counters [countEmployeeReport] ++;
break;
case 'D':
case 'd':
divisionReport();
counter [countDivisionReport] ++;
break;
case 'S':
case 's':
salaryReport();
counters [countSalaryReport] ++;
break;
case 'R':
case 'r':
retirementReport();
counters [countRetirementReport] ++;
break;
case 'Q':
case 'q':
counters [countMain] ++;
break;
else
{
menu();
countOthers++;
}
}
Am I initializing the array correctly and passing it into menu() method correctly? And am I allowed to increment the objects like that?
EDIT: I changed the code, and this is the new code
Main method:
int [] counters = new int [7];
counters [L] = 0;//listAll
counters [E] = 0;//employeeReport
counters [D] = 0;//divisionReport
counters [S] = 0;//salaryReport
counters [R] = 0;//retirementReport
counters [Q] = 0;//quit
counters [O] = 0;//others
Menu Method:
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [L] ++;
break;
case 'E':
case 'e':
employeeReport();
counters[E]++;
break;
case 'D':
case 'd':
divisionReport();
counters [D]++;
break;
case 'S':
case 's':
salaryReport();
counters [S]++;
break;
case 'R':
case 'r':
retirementReport();
counters [R]++;
break;
case 'Q':
case 'q':
counters [Q]++;
break;
}
}
else
{
menu();
counters [O]++;
}
}
And FinalStats Method:
public static void finalStats(int [] counters)
{
System.out.println("Number of times listAll() was accessed from menu() is: " + counters[L]);
System.out.println("Number of times employeeReport() was accessed from menu() is: " + counters[E]);
System.out.println("Number of times divisionReport() was accessed from menu() is: " + counters[D]);
System.out.println("Number of times salaryReport() was accessed from menu() is: " + counters[S]);
System.out.println("Number of times retirementReport() was accessed from menu() is: " + counters[R]);
System.out.println("Number of times 'Quit' was chosen from menu() is: " + counters[Q]);
System.out.println("Number of times any other key was pressed in menu() is: " + counters[O]);
}

Yes, in general. There appears to be a bug with your countOthers logic. although nesting a switch with-in an if seems an odd choice, it would be much more readable with a simple if else-if chain (and you could use Character.toLowerCase(char) to handle mixed case. Something like,
if-else
public static void menu(int[] counters) {
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available.");
System.out.println("Enter 'E' to dislpay information on a particular employee.");
System.out.println("Enter 'D' to display division information.");
System.out.println("Enter 'S' to display salary information.");
System.out.println("Enter 'R' to display retirement information.");
System.out.println("Enter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = Character.toLowerCase(first.charAt(0));
if (first1 == 'l') {
listAll();
counters[countListAll]++;
} else if (first1 == 'e') {
employeeReport();
counters[countEmployeeReport]++;
} else if (first1 == 'd') {
divisionReport();
counter[countDivisionReport]++;
} else if (first1 == 's') {
salaryReport();
counters[countSalaryReport]++;
} else if (first1 == 'r') {
retirementReport();
counters[countRetirementReport]++;
} else if (first1 == 'q') {
counters[countMain]++;
} else {
menu();
counters[countOthers]++; // <-- instead of countOthers++
}
}
switch-case
It is also possible to express the above if-else chain with switch-case and something like,
switch (Character.toLowerCase(first.charAt(0))) {
case 'l':
listAll();
counters[countListAll]++;
break;
case 'e':
employeeReport();
counters[countEmployeeReport]++;
break;
case 'd':
divisionReport();
counter[countDivisionReport]++;
break;
case 's':
salaryReport();
counters[countSalaryReport]++;
break;
case 'r':
retirementReport();
counters[countRetirementReport]++;
case 'q':
counters[countMain]++;
break;
default:
menu();
countOthers++;
}

Related

Adding a loop to a displayed menu so that it is displayed repeatedly until the last option is selected and stop the loop

I have created a display menu and want to add a loop to continuously display the menu until the last option is selected. Not sure if I am doing it right.
Let me know if there is anywhere I can add on thanks!
import java.util.Scanner;
public class loopTest
{
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit");
System.out.println("Please enter your choice: ");
}
public void start()
{
Scanner console = new Scanner(System.in);
String s = "";
while(s < size())
{
displayMenu();
console.nextLine();
switch (s.charAt(0))
{
case 'A': System.out.println("A. Option #A"); break;
case 'B': System.out.println("B. Option #B"); break;
case 'C': System.out.println("C. Option #C"); break;
case 'D': System.out.println("D. Option #D"); break;
case 'X': System.out.println("X. Exit"); break;
default: System.out.println("Error, please enter a valid
character");
}
}
s++;
}
}
consider using a boolean variable
boolean wantToExit = false;
while (!wantToExit ) {
.... // switch
case 'X':
wantToExit = true;
System.out.println("X. Exit");
break;
}
note
s is a string, there is no < comparator nor s++ incrementor
Also, you are not assign a value to s from the Console input

How to set up a boolean in a user menu?

I'm trying to set up a boolean flag so that the user must enter 'M' (Mark the student answers) before they are able to choose 'S' and 'Q'. If they choose these, there should be a message saying "Please mark the answers before inputting statistics". The rest of the options should always be available for the user but I'm not sure how to set up a boolean so that the user must choose 'M' before choosing 'S' and 'Q'. Anyone know how to do this? Here is my code so far:
public class Marker_Menu
{
public static void main(String args[])throws IOException
{
Quiz_Marker input2 = new Quiz_Marker();
char arg[]= null;
System.out.println ("Welcome to the Quiz Grading System \n");
char choice = menu();
while(choice != 'E')
{
switch (choice)
{
case 'C':
input2.corAnsPrint();
break;
case 'A':
input2.stuAnsPrint();
break;
case 'M':
input2.quizMarking();
break;
case 'S':
input2.stuStatsPrint();
break;
case 'Q':
input2.quesStatsPrint();
break;
default:
System.out.println("Your choice is invalid");
}
choice = menu();
}
System.out.println("Thank you for using the Quiz Marker System");
System.exit(0);
}
public static char menu() throws IOException
{
System.out.println ("Please enter your choice \n" +
" C - Print Correct Answers \n" +
" A - Print Student Answers \n" +
" M - Mark the Student Answers \n" +
" S - Produce the Quiz Statistics \n" +
" Q - Produce Question Statistics \n" +
" E - Exit the System");
Scanner input = new Scanner (System.in);
char choice = input.next().toUpperCase().charAt(0);
return choice;
}
}
Just create a boolean variable, set it when 'M' is selected, and test it if 'S' or 'Q' is selected:
public static void main(String args[])throws IOException
{
boolean mSelected = false;
...
while(choice != 'E')
{
switch (choice)
{
...
case 'M':
mSelected = true;
input2.quizMarking();
break;
case 'S':
if (mSelected) {
input2.stuStatsPrint();
} else {
System.out.println("Please mark the answers before inputting statistics");
}
break;
case 'Q':
if (mSelected) {
input2.quesStatsPrint();
} else {
System.out.println("Please mark the answers before inputting statistics");
}
break;
...
}
...

Java error: method in class cannot be applied to given types

I am just trying to call the methods to the main for each switch when it happens, but i just get the error message everytime i try to call any methods, not trying to return anything. ex. if the user enters a or A i want to call the add method to main
public static void main(String[] args)
{
char character;
Scanner keyboard = new Scanner(System.in);
while (character != 'E' || character != 'e')
{
System.out.println(" A:Addition \n S:Subtraction \n M:Multiplication \n D:Division \n R:Modulus \n E:exit");
switch (character)
{
case 'a':
case 'A':
System.out.println("your choice A");
add();
break;
case 's':
case 'S':
System.out.println("your choice S");
subtraction();
break;
case 'm':
case 'M':
System.out.println("your choice M");
multiplication();
break;
case 'd':
case 'D':
System.out.print("your choice D");
division();
break;
case 'r':
case 'R':
System.out.println("your choice R");
modulus();
break;
default:
System.out.println("Error: please enter a valid letter");
break;
}
}
}
public static void add(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a + b;
System.out.println(a + "plus" + b + "is" + total );
}
public static void subtraction(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a-b;
System.out.println(a + "minus" + b + "is " + total);
}
public static void multiplication(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a*b;
System.out.println(a + "times" + b + "is " + total);
}
public static void division(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a/b;
System.out.println(a + "divided" + b + "is " + total);
}
public static void modulus(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total= a%b;
System.out.println(a + "modulus" + b + "is " + total);
System.out.println("The program is terminating");
}
}
you're calling the method but you didn't include an argument
take a look at this.
public static void add(Scanner keyboard)
you have an argument, so you must include an argument when calling this method
so
you must call the method like this.
add(keyboard);
You have defined the method which takes Scanner as argument but you are calling the methods with no args.
All the method you are using are supposed to receive a Scanner object while you pass no argument.
For example you call add(); while it signature is
public static void add(Scanner keyboard)
Which is why you get the error.
Instead, use add(keyboard) and repeat the same for substraction, multiplication, division and modulus methods.
So that your switch would now look like
switch (character) {
case 'a':
case 'A':
System.out.println("your choice A");
add(keyboard);
break;
case 's':
case 'S':
System.out.println("your choice S");
subtraction(keyboard);
break;
case 'm':
case 'M':
System.out.println("your choice M");
multiplication(keyboard);
break;
case 'd':
case 'D':
System.out.print("your choice D");
division(keyboard);
break;
case 'r':
case 'R':
System.out.println("your choice R");
modulus(keyboard);
break;
default:
System.out.println("Error: please enter a valid letter");
break;
}
You are missing the arguments in the method call.
case 'a':
case 'A':
System.out.println("your choice A");
add(keyboard); // Add arguments.
break;

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

How to use loops in Java

I need help on how to use for-loops in Java
This is an assignment for class, so I'd rather just be pointed in the right direction instead of given an answer.
"List of valid seven dwarfs: Sleepy, Bashful, Doc, Sneezy, Happy, Grumpy, Dopey
Pool of random characters, non-valid Dwarfs: Lion-O, Cheetara, Panthro, Tigra, Snarf, Donald Duck, Mickey Mouse, Minnie Mouse, Goofy, Heathcliff, Huey, Dewey, Louie, Scrooge McDuck,
Declare these variables:
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
Print a list of three choices to the console. Ask the user to pick the correct dwarf of the three choices.
The list of three choices will include two names from the random characters list and one name from the seven dwarfs.
You will create a switch statement to handle the choice selection
When the wrong case is selected then decrement the int variable called counter and print to the console “wrong selection”
When the correct case is selected then change the corresponding boolean variable to true (ie.. firstSelection, secondSelection, etc) and print to the console “Hi Ho, you picked the correct one”
The default case will print a statement to the console “invalid selection”
Create a loop that will perform this seven times until you covered all seven dwarfs.
Use a for loop
Recreate the loop again using a do-while loop
Recreate the loop again using a while loop
At the end, create an if-else statement. This statement will have short circuit &&’s that will test all of the Boolean variables. If true, print a statement to the console “You earned a gold star!”. Else, print a statement to the console “You did not get all correct”. "
I completed the previous assignment, which was just this specification without the loops, with no problem. However I really don't understand how the professor wants us to integrate the loops into the problem. The only thing I can think of is that he wants up to create a loop seven times that somehow asks about a different dwarf each of the seven times. Is that even possible? Can you change the content of the loops as you are running through it? I feel like I am just not even thinking about this correctly.
Here is my code from the previous assignment, sans loops:
import java.util.Scanner;
public class SevenDwarfs {
public static void main(String[] args) {
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Sleepy");
System.out.println("2 Lion-O");
System.out.println("3 Cheetara");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hi Ho, you picked the correct one");
firstSelection = true;
break;
case 2:
System.out.println("Wrong selection");
--counter;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Panthro");
System.out.println("2 Bashful");
System.out.println("3 Tigra");
Scanner input2 = new Scanner(System.in);
int choice2 = input2.nextInt();
switch (choice2) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
secondSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Snaf");
System.out.println("2 Doc");
System.out.println("3 Donald Duck");
Scanner input3 = new Scanner(System.in);
int choice3 = input3.nextInt();
switch (choice3) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
thirdSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Mickie Mouse");
System.out.println("2 Sneezy");
System.out.println("3 Minie Mouse");
Scanner input4 = new Scanner(System.in);
int choice4 = input4.nextInt();
switch (choice4) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fourthSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Heathcliff");
System.out.println("2 Happy");
System.out.println("3 Goofy");
Scanner input5 = new Scanner(System.in);
int choice5 = input5.nextInt();
switch (choice5) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fiveSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Huey");
System.out.println("2 Grumpy");
System.out.println("3 Dewey");
Scanner input6 = new Scanner(System.in);
int choice6 = input6.nextInt();
switch (choice6) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sixSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Scrooge McDuck");
System.out.println("2 Dopey");
System.out.println("3 Louie");
Scanner input7 = new Scanner(System.in);
int choice7 = input7.nextInt();
switch (choice7) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sevenSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
if (firstSelection == true && secondSelection == true
&& thirdSelection == true && fourthSelection == true
&& fiveSelection == true && sixSelection == true
&& sevenSelection == true) {
System.out.println("You earned a gold star!");
} else {
System.out.println("\nYou did not get all correct.");
}
}
}
The fact that you realized you might be thinking about the concept incorrectly and asked for help is a good thing.
Read the following to get familiar with loops in Java.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To answer your question, yes, you can change the content of a loop as you run it. That's what variables are for. You can modify their values as your program runs. Look at this sample. The variable i increments with every iteration of the loop. The variable outsideLoop also changes inside the loop. Play with this and you'll start to understand.
class ForDemo
{
public static void main(String[] args)
{
int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
outsideLoop += i;
System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);
}
}
You've got a good starting point for the process of printing the selection, getting user input, and validating user input. Repeat that chunk (in a loop) 7 times.

Categories

Resources