Please have a look on my code its showing code not reachable.
private static void createUser() {
HashMap<String, String> membership = new HashMap<String, String>();
System.out.println("Enter the Name of the User: ");
String nameOfUser=sc.next();
System.out.println("Enter the Membership tier which you prefer");
System.out.println("1. Member - 5 % discount \n 2. Bronze - 10 % discount \n 3. Silver - 15% discount \n "
+ "4. Gold - 20 % discount \n 5. Platinum - 25 % discount");
String typeOfMembership = null;
while(true){
int memberChoice=sc.nextInt();
switch(memberChoice){
case 1:
typeOfMembership="Member";
membership.put(nameOfUser,typeOfMembership);
break;
case 2:
typeOfMembership="Bronze";
membership.put(nameOfUser,typeOfMembership);
break;
default:
System.out.println("Please select one of the available Member Type.");
}
}
for (Map.Entry<String, String> entry : membership.entrySet()) {
System.out.println("Member Created Successfully with name "+entry.getKey()+" and "+entry.getValue()+" tier.");
}
}
Its showing code unreachable from this line onwards
for (Map.Entry<String, String> entry : membership.entrySet()) {
You have an infinite loop while(true) so you will never reach the for loop.
Note: the breaks you have will only break the switch.
Suggestion:
One way to fix it is to exchange the hard coded true, to something like isMemberSelected that you set to false in the default case. You could probably also switch to a do-while-loop.
You could even break it out to a separate method memberships = createMembers();
I think you have an infinite loop at while(true) this will always evaluate to true hence the execution of the script will stay in the loop. Try a different loop guard which shouldn't always evaluate to true.
Related
Java. There is an online store, classes of products, constructors, etc. (I have all I need) There is also an array of products.
The switch statement provides a choice, the user need to select the number of product on the console. I want the user to be able to select several products (not only one product), so I added scanners (I hope there is nothing bad in scanner) I have a method which directs user to the main menu, is called in this code as firstMethod ();
The problem with the transition to the main menu through the switch statement. When I press 1, 3 and so on - the products are displayed, but when I press 6 then firstMethod (the method that calls the main menu in this online store) really work, but not "in time". When I press 1, the 1 case is executed, the program is waiting for my input of the next number. I press 6 (to go to main menu) and for some reason the program displays case 2. Then I press 6 and console displays case 3, and so on. Two more times and the console displays the main menu, this is really what I want to be shown right that moment when I press number 6.
Tell me please - what is wrong with that? How to go to the main menu (call the method) with this operator, or is it better to use another one? Write it please.
So I want firstMethod to work when user press 6 number. Can I do this via switch or I need another operator? Please help I will be really gratefull.
public static void switch1() {
Product[] products = {
new Fridge(),
new Fridge(),
new Fridge(),
...
...
...
};
Scanner scan = new Scanner(System.in);
System.out.println("1 - " + products[0]);
System.out.println("2 - " + products[1]);
System.out.println("3 - " + products[2]);
System.out.println("4 - " + products[3]);
System.out.println("5 - " + products[4]);
System.out.println("6 - Go to main menu");
System.out.println("Which one do u want to buy?");
int i = Scanner.nextInt();
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
case 2:
System.out.println(products[1]);
Scanner.nextInt();
case 3:
System.out.println(products[2]);
Scanner.nextInt();
case 4:
System.out.println(products[3]);
Scanner.nextInt();
case 5:
System.out.println(products[4]);
Scanner.nextInt();
case 6:
firstMethod();
}
It seems like the only visible problem is that there are no break; statements at the end of each of your case blocks.
For example:
switch (i) {
case 1:
System.out.println(products[0]);
Scanner.nextInt();
break;
...
Also, just calling Scanner.nextInt(); won’t do anything unless you use the value returned by the call.
You also said you wanted the user to be able to select multiple products, so in order to do that, you could put the switch in a loop, such as a while loop, and have it loop until a condition is met to stop it.
Edit: The following code shows a small example of what your code structure could be:
boolean loop = true;
while (loop) {
int i = scan.nextInt();
switch (i) {
case 1:
System.out.println(product[0]);
break;
//... cases 2-5 are similar to case 1
case 6:
firstMethod();
loop = false;
break;
}
}
This can be done in a much more efficient manner without a switch at all.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < products.length; i++) {
System.out.println((i + 1) + " - " + products[i]);
}
System.out.println((products.length + 1) + " - Go to main menu");
System.out.println("Which one do u want to buy?");
while (true) {
int selection = Scanner.nextInt();
if (selection > 0 && selection <= products.length) {
System.out.println(products[selection - 1]);
} else {
break;
}
}
firstMethod();
My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.
I understand that while the state is true the loop will keep running. I thought if I simply typed in loop=false, after the } bracket for the loop I could continue to code. Obviously I was wrong, it wont run anything. SOMEONE please show me how to get out of this hell of a while loop.
System.out.println("You total balance is 0.00, "
+ "please deposit coins and type done when finished");
while(loop){
if (input.hasNextInt()){
deposit = input.nextBigDecimal();}
String change = input.next();
switch (change){
case "quarter":
balance= quarter.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "dime":
balance=dime.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "nickel":
balance=nickel.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case "penny":
balance=penny.multiply(deposit);
total=total.add(balance);
System.out.println("Your balance is "+ total +" :Make addiontal deposit(s)");
break;
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
break;
default: System.out.println("There is a issue at "+change);}
} System.out.println("4");
}
}
The key is to change the loop variable so that it becomes false and will thus have you exit the while loop. So change the loop variable in the case "done" block. In that block, set loop = false;
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
loop = false; // ************ add this ************
break;
Keep in mind that the key concept is that the thing that is causing the loop to continue must be changed somehow within the loop itself. Otherwise the while loop will never end.
Three methods to break a loop.
A) set your flag variable to false:
loop = false;
Since you already have this variable, this is the much nicer (and simpler) approach.
B) use a labeled break.
label: while(true) {
// ...
switch(something) {
break label; // Without a label, it would only leave the switch!
}
}
Some people will frown upon this last solution, because it is essentially a "goto".
C) use more modular code.
In many cases, the much cleaner way is to use methods. Then you can have "break" to exit an inner loop or switch and return to actually leave the subprocedure and return a result.
This leads to easier-to-understand code, and the semantics of a return are often much more appropriate than those of a break.
Your loop will continue to go round until the loop variable is set to false. In the "done" case, just set that to false. That way, it won't loop back around again.
case"done":
System.out.println("Your total is $"+total);
fee=total.multiply(feeRate);
System.out.println("The exchance fee is 9.1% which amounts to $"+fee);
grandTotal=total.subtract(fee);
System.out.println("Your total balance minus the exchange fee is $"+grandTotal);
loop = false; // This is the line to add.
break;
You have to change the value of the variable loop inside oft the while loop to false.
I guess this should be in the case when the user types done. So in this case add the following line:
loop = false;
anywhere in the case "done": block
I've nested an IF ELSE statement inside a WHILE statement, but am confused as to why the WHILE is interpreted before the ELSE (when the IF fails). A user is asked to enter a number from 1-10 (inclusive). If the number is inside that range, the program ends. If it's outside of that range, I want to display an error and then prompt them to again enter a number.
It works well if I put the "prompt" before the WHILE, but then I have to put it again inside the ELSE statement for it to show up again. I found this question, but it didn't appear to answer the issue I'm running into. I'm admittedly a Java novice, so I apologize if I'm missing some fundamental aspect of Java.
import java.util.Scanner;
public class Rangecheck {
private static int userNumber; //Number input by user
private static boolean numberOK = false; //Final check if number is valid
//String that will be reused in the DO statement
private static String enterNumber = "Please enter a number from 1 to 10: ";
public static void main(String[] args) {
//Print string
while(!numberOK) // Repeat until the number is OK
{ System.out.println(enterNumber);
Scanner input_UserNumber = new Scanner(System.in); //input integer
userNumber = input_UserNumber.nextInt();
if (10>= userNumber && userNumber >= 1) //Check if 10>=input>=1
{
/*
** If number was valid, congratulate the user and mark numberOK true
*/
System.out.println("Good job! The number you entered is "+userNumber+".");
numberOK = true; // Congratulate user / exit loop if successful
}
else ; //if (10 < userNumber && userNumber < 1)
{
System.err.println("The number entered was not between 1 and 10!");
System.err.print(enterNumber); // Error; user retries until successful
}
}
}
}
I'd expect the System.err.println() to be evaluated in the else statement and then the whileto be evaluated, so that this gets returned:
The number entered was not between 1 and 10!
Please enter a number between 1 and 10:
I've sort of worked around this by putting enterNumber just before while, then putting a second
println in the else statement immediately following the error. It returns what I expect, but I believe I'm fundamentally misunderstanding something.
Let's suppose you have the following code:
while (whileCondition) {
//Inside while, before if
if (ifCondition) {
//Inside if
} else {
//Inside else
}
}
This cycle will execute repeatedly, until the whileCondition becomes false. Whenever the ifCondition is true, the operations inside if will be executed, otherwise the operations inside else will be executed.
Back to your problem:
Your line of
System.out.println(enterNumber);
is at the start of the while. So before the code even gets to your if, the content of enterNumber is displayed on the console. Later, your if is evaluated and if you enter, let's say 22, the condition given to the if will be false and the content of the else block will be evaluated.
The else statement is repeated before the while statement. There can however sometimes be a problem with Streams. A Stream does not necessarily print the data immediately. Especially in the case one uses two different streams, the order of printing the output data can be interleaved.
You can use:
System.err.flush();
to ensure the data is written to the console first.
Add this statement in else body:
numberOk=false;
I'm just a newbie in java, so please help me, i think the problem is in the switch stament
String customer[]=new String[2];
int old[]=new int[2];
for(i=0; i<customer.length;i++){
System.out.println("\nEnter information of customer#" +(i+1));
System.out.print("Enter customer name"+(i+1)+":");
customer[i]=data.readLine();
System.out.print("Enter old reading of costumer#"+(i+1)+":");
old[i]=Integer.parseInt(data.readLine());
}
System.out.println("\n\nSample Menu");
System.out.println("1. Display Transaction\n2.Pay Water Bill");
System.out.print("Enter your choice:");
choice=Integer.parseInt(data.readLine());
In this part the System.out.println(customer[i]+"."); is not working
switch(choice){
case 1:
System.out.println("This is to display the transaction!");
System.out.println(customer[i]+"."); \
break;
case 2:
System.out.println("This is to pay the water bill!");
break;
default: System.out.println("Exit`!");
break;
}
}
}
The problem is that when you exit your loop, the value of i is 2, not 1.
The increment expression is invoked after each iteration through the
loop.
So when accessing System.out.println(customer[i]+"."); you go out of bounds since the last element of your array is at index 1 (arrays are 0 base indexed).
If you take this snippet of code:
int i;
for(i = 0; i < 2; i++){}
System.out.print(i);
It outputs 2.
At that point variable i has incremented to 2 So you would have to reset it first. Ofcourse you get IOOB exception because you are referencing missing place in array (only places 0 and 1 exist)
This is how your code works :
for(i=0; i<customer.length;i++){
............................
............................
}
Hence, i takes values :
i is (i < customer.length)
0 YES
1 YES
2 NO <LOOP BREAKS>
Now, when it comes to the switch statement, the following happens:
switch(2) { //ALWAYS
..........
..........
}
Hence, the switch(1) case, or the System.out.println(customer[i]+".") is never reached. It's quite a common mistake.
What you need is a do while loop for your menu.
So :
// Initialize Values
for(i=0; i<customer.length;i++){
............................
............................
}
// Loop through the Options
do {
// ASK FOR USER INPUT AS YOU ARE DOING
switch(choice) { //ALWAYS
..........
..........
}
} while(choice != 1 || choice != 2);
The do while ensures that no matter what, your command will be executed for the menu, when it is given. So for example, in the do while, your default exit statement will always be printed.