Use Loop to print out each monthly rent, Threshold [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Use a Loop to print out each monthly rental from the array that falls below the user entered threshold
This was a question I received from my lecturer, I require help because I simply have no idea where to even start. Here is my complete code for the Program, it is the last case.
import java.util.Scanner ;
public class jakeGrim {
public static void main(String[] args) {
// Local variable
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
{
switch (option) {
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
{
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +(totalSum));
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
case 5:
Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
System.out.println("
break;
default:
System.out.println("Invalid selection");
break;
}
}
}while (option!=0);
}
}

Well,your program has several flaws which should be improved for better performance.
There is no need of braces before switch.So,delete the braces{ before the switch statement!
Again,there is no need of braces { in case 2 and } before break statement of case-2. You better leave it as it is.
Add these lines of code in your case 5: after deleting previous data into that.
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
Lastly,you simply need to edit do-while condition,set it as do{...}while(option>=1 && option<=5);
Also, as a matter of fact,try to indent your code properly to give it a better feel! It will make others go through your code and sincerely help you!
Correct working code :-
import java.util.Scanner;
public class jakeGrim {
public static void main(String[] args) {
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
switch (option){
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +totalSum);
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
break;
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
default:
System.out.println("Invalid selection");
break;
}
} while (option>=1 && option<=5);
}
}

Related

How to take user input using while loop asking if he/she wants to continue or exit?

I am trying to take user input and ask if the user wants to enter the gamer's information. if "yes" then take the info and if "no" then exit the program.
My code is working well except that when I am asking the user for the second time and enter "no", it is not exiting the program but instead is asking again for the gamer's name.
import java.util.Scanner;
public class A3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
double L1, L2, L3, ES;
boolean yes = true
System.out.println("Welcome to the Total XP calculation program!");
System.out.print("Do you want to enter gamer's data? Yes/No => ");
String y_n= sc.nextLine();
while (yes = true) {
if (y_n.equals("yes") || y_n.equals("Yes")) {
System.out.print("Enter gamer's name: ");
name = sc.next();
System.out.println("Enter gamer's Level XP scores separated by space: L1 L2 L3 ES => ");
L1 = sc.nextDouble();
L2 = sc.nextDouble();
L3 = sc.nextDouble();
ES = sc.nextDouble();
// calculating total score
double score = L1+L1*0.20+L2+L2*0.30+L3+L3*0.50+ES+ES*0.60;
// printing informations.
System.out.println("Gamer's name: "+name + " L1 = "+L1 + " L2 = " +L2 + " L3 = " +L3 + " ES = " +ES);
System.out.println("Final XP score with bonuses= "+score);
System.out.println("\nDo you want to enter another gamer's data? Yes/No => ");
String choice;
sc.nextLine();
choice = sc.nextLine();
switch (choice) {
case "no" :
case "No" :
System.out.println("Thank you for using the Total XP calculator!");
yes = false;
}
}
else if (y_n.equals("no") || y_n.equals("No")) {
System.out.println("Thank you for using the Total XP calculator!");
break;
}
}
}
}
I'd write it more like:
boolean quit = false;
while (!quit) {
System.out.print("Do you want to enter gamer's data? Yes/No => ");
String y_n= sc.nextLine();
if (y_n.toLowerCase().equals("yes") ) {
System.out.print("Enter gamer's name: ");
name = sc.next();
System.out.println("Enter gamer's Level XP scores separated by space: L1 L2 L3 ES => ");
L1 = sc.nextDouble();
L2 = sc.nextDouble();
L3 = sc.nextDouble();
ES = sc.nextDouble();
sc.nextLine(); // clear out line feed
// calculating total score
double score = L1+L1*0.20+L2+L2*0.30+L3+L3*0.50+ES+ES*0.60;
// printing informations.
System.out.println("Gamer's name: "+name + " L1 = "+L1 + " L2 = " +L2 + " L3 = " +L3 + " ES = " +ES) ;
System.out.println("Final XP score with bonuses= "+score) ;
}
else if (y_n.toLowerCase().equals("no")) {
quit = true;
}
else {
System.out.println("Invalid response!");
}
}
System.out.println("Thank you for using the Total XP calculator!");

How to go back to the beginning of a code without ending it?

I want to go back to the beginning of my code in order to print multiple things and allow people to add multiple “drawings” to a picture without ending the code
Here’s my code:
package com.company;
import java.util.Scanner;
public class Art {
public static void main(String[] args) {
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
String response1 = scan1.nextLine();
}
}
Use a do-while loop to go inside the loop at least once.
You are asking at the end if he wants to add more, you should give the User a choice like type in 'Y' for more.
The 'Y' is here just a dummy value you can replace it with anything you want this should just be an example.
Then you compare the typed in value in the condition of your while()
When the value you are asking for was typed in then go ahead and loop through it again.
import java.util.*;
public class MyClass {
public static void main(String[] args){
String response1;
do{
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
response1 = scan1.nextLine();
}while(response1.equals("Y"));
}
}
Surround your code with while(true)
while (true)
{
// add your code here
}
You can break the loop by using 'break;'

How do I get the menu program to restart after completing a selection?

My program is stuck in an infinite loop after a selection is made and completed. It needs to restart and go through the menu options again. Any help would be greatly appreciated.
public static void main(String[] args) {
// TODO Auto-generated method stub
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int choice = input.nextInt();
int count = 0;
while (choice < 1 || choice > 6){
count ++;
System.out.println("I'm sorry, " +choice+ " is not a valid option.\n");
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
choice = input.nextInt();
if (choice >= 1 && choice <= 6){
continue;
}
else if (count == 2){
System.out.println("Please try again later.");
System.exit(0);
return;
}
}
do
{
switch (choice)
{
case 1: choice = 1;
System.out.print("What is the first number? ");
int firstAdd = input.nextInt();
System.out.print("What is the second number? ");
int secondAdd = input.nextInt();
System.out.println("Answer: " +(firstAdd + secondAdd));
break;
case 2: choice = 2;
System.out.print("What is the first number? ");
int firstSub = input.nextInt();
System.out.print("What is the second nubmer? ");
int secondSub = input.nextInt();
System.out.println("Answer: " +(firstSub - secondSub));
break;
case 3: choice = 3;
System.out.print("What is the first number?" );
int firstMult = input.nextInt();
System.out.print("What is the second number? ");
int secondMult = input.nextInt();
System.out.println("Answer: " +(firstMult * secondMult));
break;
case 4: choice = 4;
System.out.print("What is the first number? ");
double firstDiv = input.nextInt();
System.out.print("What is the second number? ");
double secondDiv = input.nextInt();
while (secondDiv == 0){
System.out.println("I'm sorry, you can't divide by zero.");
break;}
{
System.out.println("Answer: " +(firstDiv / secondDiv));
break;
}
case 5: choice = 5;
System.out.println(Math.random() * 10 + 1);
break;
case 6: choice = 6;
System.out.println("Goodbye!");
System.exit(0);
return;
}
}while (choice >=1 && choice <= 6);
}
I've tried a few different options that I found in my book, but they seem to cause more errors in other areas. I don't know if there is a different statement than "break;" to use to restart the menu because this is my first time using cases.
Enclose everything after the scanner instantiation in a while loop.
Specifically,
while (true) {
// your code
if (choice == 6)
break;
}
FIXED: Also remove the do {} while() loop. Your loop is infinite because "choice" does not change in the loop.

How to set limit on input from 0-100 Java

So this is my code: I need to set a limit on the input of the grades in the switch statement so that it will not go over 100 and under 0. If anyone could help, that would be incredible. Thanks.
import java.util.Scanner;
public class assigment1{
static Scanner key = new Scanner(System.in);
public static void main(String[] args){
int number;
System.out.println("Student Grade System");
System.out.println("====================");
System.out.println("");
System.out.println(" 1) Enter student details");
System.out.println(" 2) Dsiplay student grades");
System.out.println(" 3) Display student statistics");
System.out.println(" 4) Display full transcript");
System.out.println(" 0)Exit system");
System.out.println(" ");
System.out.print("Select an option [0-4]>>");
Scanner input= new Scanner(System.in);
number=input.nextInt();
switch(number){
case 1:
System.out.print("Entering Student Detials");
System.out.print("========================");
System.out.print(" Student number: ");String a =key.nextLine();
System.out.print(" Programing Grade: ");number=input.nextInt();
System.out.print(" web Development Grade: ");number=input.nextInt();
System.out.print(" Mathematics Grade: ");number=input.nextInt();
System.out.print(" Critical Thinking Grade: ");number=input.nextInt();
System.out.print(" Operating System Grade: ");number=input.nextInt();
System.out.print(" Computer Archetecture Grade: ");number=input.nextInt();
break;
case 2:
System.out.println("Display stuent grades");
break;
case 3:
System.out.println("Display student statistics");
break;
case 4:
System.out.println("Display full transcript");
break;
default:
System.out.println("Thanks for using the system");
break;
You could write a function like this:
(didn't tried this code)
private int getNumberFrom0To100() {
Scanner in = new Scanner(System.in);
int result;
do {
result = in.nextInt();
} while(result < 0 || result > 100);
return result;
}
and use it at your needed position:
number = getNumberFrom0To100();
Else have a look at the delimiter function where you can pass regex:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
Scanner s = new Scanner(input).useDelimiter("^[1]?[0-9]?[0-9]$");
you can use this code , You must write This code Before Switch Case :
Scanner in = new Scanner(System.in);
System.out.println("Enter The number");
int score = in.nextInt();
while(score<0||score>100){
System.out.println("You Entered the wrong number , Enter The number Again :");
score = in.nextInt();
}
Here is a one-liner to fit in your code's logic and display
Solution
while((number = Math.abs(input.nextInt())) > 100)
System.out.println("Invalid input. Try Again");
Console
537
Invalid input. Try Again
-537
Invalid input. Try Again
-2
Attention
If user enters -2 for example, it will take it as a valid input since 2 which is abs(-2) is contained between 0 and 100.

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Categories

Resources