I am a little stuck. I have grasped the concept of methods; understanding their purpose but still unsure on how to code it. Below is part of my code I kindly need guidance on. I am trying to create a method which can hold roles and depending on which switch option is selected it will return the the amount. I have four employment roles which all have different payscales. I have commented the errors on the role method. If I can correct this and make it work then I can complete this program :)
import java.util.Scanner;//allows input from the keyboard
import java.text.*;
class Wage_Method_2
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("0.00");
double normHrs = 0, overHrs = 0, bonusHrs = 0, actualHrs = 0, cash=0, overPay =0, bonusPay = 0, grossWage = 0,vat23 = 0, netWage =0;
String empName,nextEMP = "y", manager, superVisor, teamLead, general;
while (nextEMP.equalsIgnoreCase("y"))
{
System.out.print("Please enter an employee's first name: ");
empName = input.next();//their name
System.out.print("Please enter "+empName+"'s employment ID: ");
int job = input.nextInt();
System.out.print("Please enter their total hours worked: ");
actualHrs = input.nextDouble();
double basicPay = rate (5.75)*actualHrs;
System.out.println("Basic Pay: "+basicPay);
System.out.println("\nWould you like to log hours for another employee?");
nextEMP = input.next();
if (nextEMP.equalsIgnoreCase("n"))
{
System.out.println("Thank you, the hours have been successfully logged.");
}
}// end of whileloop
}// end of class
public static double rate (double cash String jobrole)// when compiling these errors appear: error: ')' expected and error: <identifier> expected
{
switch (jobrole)
{
case 1:
cash = 5.75;
case 2:
cash = 5.75*1.1;
case 3:
cash = 5.75*1.25;
case 4:
cash = 5.75*1.42;
break;
}
return (cash);
}
}// end of program
There are a few errors here:
The parameter list must be separated by commas
You cannot switch with a String and have the values be integers. (Also note switching on strings was first introduced in Java SE7.)
You don't break out of the switch statement. (This isn't a compile time error, but almost definitely a runtime error, that is the code isn't doing what you expect.)
.
public static double rate (double cash, String jobrole)
// ^
{
switch (jobrole)
{
case "1": return 5.75;
case "2": return 5.75*1.1;
case "3": return 5.75*1.25;
case "4": return 5.75*1.42;
default: return 0; // some default.
}
}
Others have stated that the method has to be in a class. It is. The comments in the code is just wrong. The error you are getting on the line is because you don't have the comma.
In your code, you never break out of the switch. In a switch statement, execution falls through from case to case, so if the value of jobrole is "3" then your code would execute:
cash = 5.75*1.25;
cash = 5.75*1.42;
break;
So to fix this, we just return the value instead of setting a local variable. Another option would be to just break; after each case.
Also note, in this scenario, you don't really need to pass the value cash in, since it is never used anyway (it is just overwritten).:
public static double rate( String jobrole )
{
//...
}
You need to define a method inside your class, not outside it. Move it inside the outer closing curly bracket.
There are a number of other problems in your code as well.
I recommend getting an IDE like Netbeans, they are a free download and the syntax highlighting and inline error reporting will make your life much easier. I suggest Netbeans as it is one of the most intuitive to use, you can also consider other options such as Eclipse though.
Load the file into the editor and look at each of the errors in turn. Google them and find out what they mean, then try and correct them.
Related
I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception
java.util.NoSuchElementException
for sample input
5
1 2 3 4 5
here first line contains number of elements (in this case its 5),and next line contains elements.
while taking input inside the for loop in the class Election ,i am getting exception.
I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.
import java.io.*;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
input.nextLine();
Election obj = new Election(n);
obj.getVotes();
}
}
class Election {
int n,v1,v2,v3,v4,v5,d;
public Election(int n) {
this.n = n;
v1=v2=v3=v4=v5=d=0;
}
public void getVotes() {
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i < 1 ; i++) {
int var = sc.nextInt();
switch(var) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
}
Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.
Here is a simple deviation of the code you provided, but reaches the desired result!
I'll walk you through this:
public class MyTest {
public static void main(String[] args) {
//First of all, we need an instance of an Election-type object, so
//that we can call its methods and get votes from users.
Election e = new Election();
//Now we can easily call the method getVotes(), as defined in Election class.
//What happens here, is that the program will 'jump' to the getVotes() method
//and it will execute every line of code in that method. Then it will
//'return' to where it 'left off' in the main() method. Since getVotes()
//is of type 'void', it will not return anything. It will just 'jump' back.
e.getVotes();
//Now, you can use testResult() method, to see the values of the variables.
e.testResult();
}
}
Now, let's take a look at the class Election and how it works.
public class Election {
private final int VOTES_NUM = 1;
private int v1,v2,v3,v4,v5,d;
public Election() {
v1=v2=v3=v4=v5=d=0;
//print now, just to show that all variables = 0
testResult();
}
//Simple method that prints value of each variable. We use this for testing
public void testResult(){
System.out.println("v1 = "+v1);
System.out.println("v2 = "+v2);
System.out.println("v3 = "+v3);
System.out.println("v4 = "+v4);
System.out.println("v5 = "+v5);
System.out.println("d = "+d);
}
private int getInput(){
//First of all, we need a Scanner to take user input.
//You do that in your own code too. We simply move it in this method instead.
Scanner input = new Scanner(System.in);
//You also need variable to hold the user input.
//(Always give meaningful names to all entities)
int userInput;
System.out.print("Please enter vote number here: ");
//the next part has to be in a try-catch block,
//to avoid exceptions like InputMismatchException, etc..
try{
//Get user input
userInput = input.nextInt();
}
//If user enters letter, or symbol, or something else that isn't an integer,
//then inform them of the mistake they made and recursively call this method,
//until they get it right!
catch (InputMismatchException ime){
System.out.println("Please enter only a single number");
return getInput();
}
//If all goes well, return the user input
return userInput;
}
public void getVotes() {
//'VOTES_NUM' is a constant that defines the times the
//loop will iterate (like Macros in 'C')
for(int x=0; x<VOTES_NUM; x++)
int n = getInput();
//then let the switch statement increment one of the variables
switch(userInput) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.
I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:
public static void main(String...args){
Election election = new Election(10);
election.getVotes();
System.out.println(election.v1);
System.out.println(election.v2);
System.out.println(election.v3);
System.out.println(election.v4);
System.out.println(election.v5);
System.out.println(election.d);
}
My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:
2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d
I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)
I have no code to paste since all I have is a template of my methods to be used. Hopefully this isn't too broad because I've looked all over and haven't received the answer I'm needing.
Many have seen or heard of a "Magic 8 Ball" program. A user asks a question, and they receive a random answer in return. I could have written the code easily with one method, but now we've delved into using multiple methods and I'm missing a piece of the puzzle.
The rules of this program:
1) I have to create at least three methods: the main, an input method, and an output method.
2) I have to use a switch statement for the random answers.
3) I have to use a while loop (or a do-while) to prompt the user to either ask another question, or quit.
I think my only problem lies in where to place each piece of the code. I'm going to need to call a Scanner. That's no big deal. I know how to do the switch statement. I know how to randomize the output. I'm most likely going to use a boolean for the keep going/quit part. But where do I actually PLACE the scanner? The boolean? In the main? In an input method? What about the processing section for the randomization? Are all my variables declared in the main so they spread throughout?
I hope my question makes sense.
Creating Scanner once either in main, or in the constructor as a class level object will be much cheaper than creating every time you call the input method. If created at class level it can be used directly in input method, otherwise if it is created in main method it can be passed as an argument to the input method.
Boolean can be in the input method because you are directly comparing the input and you have no more use for it.
When you have an object, especially an expensive one, it is better to create it only once wherever applicable, or create it as few times as possible.
Excuse my sloppy code, and ignore the case names. They are temporary since I will be renaming them. I tried every scenario after compiling. I asked a question, it answered, and it asked if I wanted to ask another. I asked another, it repeated the prompt. I answered "n", and it said "Thanks for playing. Goodbye", and stopped running. Here is my code. Problem solved.
import java.util.Scanner;
public class MagicBall {
public static void main(String[] args) {
int random = 0;
boolean playAgain = true;
while (playAgain) {
askAnother(random);
}//end while
}//end main
public static void askAnother(int r) {
System.out.print("Hello! What is your question? ");
Scanner input = new Scanner(System.in);
String question = input.nextLine();
String yes_or_no;
String next_question;
randomAnswer(r);
boolean playAgain = true;
while(playAgain) {
System.out.println("Would you like to ask another question? Y to ask, N to quit.");
yes_or_no = input.nextLine();
if (yes_or_no.equalsIgnoreCase("Y")) {
System.out.println("What is your next question?");
next_question = input.nextLine();
randomAnswer(r);
}//end if
else if (yes_or_no.equalsIgnoreCase("N")) {
playAgain = false;
System.out.println("Thanks for playing. Goodbye.");
System.exit(0);
}
else {
System.out.println("Invalid Input. Please enter Y or N.");
continue;
}//end else
}//end while
}//end input method
public static int randomAnswer(int r1) {
r1 = (int)(Math.random() * 9);
switch(r1) {
case 0: System.out.println("Yes"); break;
case 1: System.out.println("Yes1"); break;
case 2: System.out.println("Yes2"); break;
case 3: System.out.println("Neutral"); break;
case 4: System.out.println("Neutral1"); break;
case 5: System.out.println("Neutral2"); break;
case 6: System.out.println("No"); break;
case 7: System.out.println("No1"); break;
case 8: System.out.println("No2"); break;
}//end switch
return r1;
}//end output method
}//end MagicBall class
This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.
I'm making a school assignment and this time around I thought about using a switch statement since it looked more efficient.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
This is my code for the entire class so far:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
private int option;
public static void main(String[] args) {
Test t = new Test();
t.start();
t.optionMenu();
}
public void start() {
System.out.println("Make your choice:");
System.out.println("1: Play");
System.out.println("2: Options");
System.out.println("3: Exit");
}
public void optionMenu() {
try {
Scanner sc = new Scanner(System.in);
this.option = sc.nextInt();
System.out.println(this.option);
} catch (InputMismatchException e) {
System.out.println("Please enter a number");
optionMenu();
}
switch (this.option) {
case 1:
System.out.println("Game starting...");
break;
case 2:
System.out.println("Loading options");
break;
case 3:
System.out.println("Game exiting...");
System.exit(0);
break;
default:
System.out.println("Enter a valid number (1, 2 or 3");
break;
}
}
}
Any help would be much appreciated, thanks!
When you call sc.nextInt() without first asking if (sc.hasNextInt()), you are open to some strange behavior when end-users start typing unexpected input, such as letters. In this case the scanner would not advance its reading pointer, so your program will get stuck reading the same incorrect output.
To fix this issue, add a loop that "clears out" the invalid entry before attempting to read an int again, like this:
while (!sc.hasNextInt()) {
System.out.print("You need to enter an integer.");
sc.nextLine(); // Clear out the bad input
}
int val = sc.nextInt(); // At this point we know that sc.hasNextInt(), because that's the loop condition
Another point is that it is not a good idea to do with recursion what can be done with iteration: the recursive call to optionsMenu is going to accumulate as many levels of invocation as the number of times the end-user enters an incorrect value, so a very persistent user could theoretically force a stack overflow on your program by entering invalid data repeatedly.
Using the code fragment above would free you from the need to call optionsMenu recursively, and also from catching the input exception.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
I'm not sure what you mean here. Firstly, your idea works, this code should be fine!
Second, if you enter anything besides just the number 1, 2, or 3, you will go to the "default:" block of code. Since you are prompting the user again if they fail, typing "a" or "a1" into the prompt just shows the menu again. The user needs to just type "1", "2", or "3" to successfully select a menu option.
I don't think my switch statement is doing anything with my code, I'm new to java so I'm not sure how to use a switch statement in a while loop. I'm trying to take each grade/credit entered so I can find the GPA, but I added a System.out.print for the grades and it says it's worth 0 no matter what gets entered. Please help!
package exercises;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class GPA_Calculator {
public static void main(String[] args)
{
String greeting = "Hello, this program will calculate your GPA. You will be asked \n"+
"to enter your letter grade for each class, then you will be asked to enter \n"+
"the corresponding number of credits for that class. Once all the grades and credits\n"+
"have been entered, the program will display your GPA.";
JOptionPane.showMessageDialog(null,greeting,"Greeting - Introduction",1);
char gradeEntered;
String grade = "";
String creditEntered = "";
String inputGrade = "";
String inputCredit = "";
String enterGradePrompt = "Enter your letter grade (A, B, C, D, F)\n"+
"Enter Q to display your results\n\n";
String enterCreditPrompt = "Enter the credit hours for your course (0, 1, 2, 3, 4, 5, 6)\n"+
"Enter Q to display your results\n\n";
int points = 0, sum = 0, credits = 0, gradeCount = 0;
while(!inputGrade.toUpperCase().equals("Q"))
{
inputGrade = JOptionPane.showInputDialog(null,enterGradePrompt,"Enter grade",1);
gradeEntered = inputGrade.charAt(0);
grade += inputGrade.toUpperCase()+"\n";
inputCredit = JOptionPane.showInputDialog(null,enterCreditPrompt,"Enter grade",1);
creditEntered += inputCredit+"\n";
if(inputCredit.toUpperCase().equals("Q"))
continue;
credits = Integer.parseInt(inputCredit);
credits++;
switch (gradeEntered){
case 'A': points = 4;
break;
case 'B': points = 3;
break;
case 'C': points = 2;
break;
case 'D': points = 1;
break;
case 'F': points = 0;
break;
}
sum += gradeEntered;
gradeCount++;
}
// Prevents "Q" from being printed in results
grade = grade.substring(0,grade.length()-2);
creditEntered = creditEntered.substring(0,creditEntered.length()-2);
DecimalFormat df = new DecimalFormat("#.##");
double gpa = sum / gradeCount;
String results = "The courses you entered are:\n\n"+
"Grade "+"Hours \n"+
grade+" "+creditEntered+"\n"+
"Resulting in a GPA of "+df.format(gpa)+"\n\n"+
"This program will now terminate!";
JOptionPane.showMessageDialog(null, new JTextArea(results),
"results from the Invitation list generator",1);
}
}
The problem is that your switch statement is checking the value of grade, but your input is stored in inputGrade. The former is never reassigned from the empty string, so points never gets incremented.
EDIT: To expand on the comment below:
the conditional in either a while or do/while loop isn't being checked. You're checking it inside the loop and breaking out, which is fine, as you can just make an infinite loop and let the break terminate it. However, it shouldn't be duplicated in the loop conditional.
You should do check that condition early. There's no sense in performing anything inside the loop if the user enters 'q' (also, then, you don't have to have the part where you try to strip it afterwards).
Also, you should always try to keep your variables as locally as possible. There's no need to have anything but the aggregators (totalXxx and yyyEntered in this case) outside of the loop. It just makes it confusing for you in this case, as it's masking the source of your problem. When the switch statement hits the first time, it checks the empty string. The second time, it checks the first string. When you hit 'q', it breaks, and skips your last input. If these input variables were declared inside the loop, that would be immediately apparent.
Finally, while I'm here, you have an error in your gpa calculation. The points per score should take the weight of credits as a positive, not a negative. Something like:
sum(grade * credits) / sum(credits)
I can post fixed code if you want, but since I suspect this is an academic exercise, it would be more beneficial if you came to the solution yourself.
Your switch statement is using grade which seems to be never written to. It's always "".
You get inputGrade, but you don't write to grade itself.
As it is always "", you always get nothing from your switch
You are appending each grade to your gradeEntered
gradeEntered += inputGrade.toUpperCase()+"\n"; // at a point this is something like A\nB\nC\nD\nE.... so it will not match anyway
switch (gradeEntered) {
case "A": points = 4;
break;
case "B": points = 3;
break;
case "C": points = 2;
break;
case "D": points = 1;
break;
case "F": points = 0;
break;
}
so most of the times it will not match to any of your cases.
Either you have to have a separate char for grade and use it in the switch or first use switch and then append it to your variable
You are adding a newline ("\n") to your input, (inputGrade.toUpperCase()+"\n";) so none of your cases are valid.
That is, "A" does not equal "A\n"
I think you should not use "gradeEntered" and instead use:
switch (inputGrade.toUpperCase())
especially since after running the loop more than once, your "gradeEntered" string will start to look like this: "A\nB\nF\nQ\n", which is very far removed from all your cases.
Also, switching on strings is not good practice - it is a newish development in java, and won't be supported by computers running older versions fo java - though for your own use, if the compiler doesn't complain then it is fine. Still, better to get in the habit of switching on chars or ints, since most other programming languages won't let you switch on strings.