I'm working in Java. So what I'm trying to do is, take the user input from subscriberPackage
public static String subscriberPackage() { //Method to get the customers name
Scanner sc = new Scanner(System.in);
System.out.println("\nPlease choose a package the customer would like:");
System.out.println("Enter Bronze, Silver or Gold to select a package.");
String subscriptionPackage = sc.nextLine(); //Get subscription package from the user
while (!(subscriptionPackage.equalsIgnoreCase("Bronze") || subscriptionPackage.equalsIgnoreCase("Silver") || subscriptionPackage.equalsIgnoreCase("Gold"))) {
System.err.println("This is not a valid package!");
System.err.println("Please try again!");
System.out.println("Please choose a package the customer would like:");
System.out.println("Bronze, Silver or Gold.");
subscriptionPackage = sc.nextLine();
//If the package entered is not Bronze, Silver or Gold, the user is asked to re-enter till the while condition is met
}
return subscriptionPackage; //Returns the subscription package to the newSubscription method
}
and subscriberDuration
public static int subscriberDuration() { //Method to get the subscription duration
Scanner sc = new Scanner(System.in);
System.out.println("\nPlease choose the subscription duration");
System.out.println("It must be either 1, 3, 6 or 12 months.");
System.out.println("Please now enter the subscription duration the customer would like");
int subscriptionDuration = sc.nextInt(); //Get the subscription duration from the user
while (subscriptionDuration != 1 && subscriptionDuration != 3 && subscriptionDuration != 6 && subscriptionDuration != 12) {
System.err.println("This is not a valid duration, please try again!");
System.err.println("It must be either 1, 3, 6 or 12 months.");
subscriptionDuration = sc.nextInt();
//If the duration entered is not 1, 3, 6 or 12, the user is asked to re-enter till the while condition is met
}
return subscriptionDuration; //Returns the subscription duration to the newSubscription method
}
and calculate a cost in subscriberBill.
private static int subscriberBill(String subscriptionPackage, int subscriptionDuration) {
int subscriptionCost = 0;
int[] subsBronzePackageCosts = new int[1000];
subsBronzePackageCosts[0] = 600;
subsBronzePackageCosts[1] = 500;
subsBronzePackageCosts[2] = 400;
subsBronzePackageCosts[3] = 300;
int count = 0;
for(int i = 1; i <= 12; i+=3){
if (subscriptionPackage.equals(subscriptionPackage) && (subscriptionDuration == subscriptionDuration)) {
subscriptionCost = (subsBronzePackageCosts[i] + i + count);
count++;
System.out.println("\nThe cost of this subscription is: " + subscriptionCost);
return subscriptionCost;
}
}
return subscriptionCost;
}
}
I have managed to pass through this information and started adding the costs of the Bronze tier subscriptionPackage. I have done this using an array:
int[] subsBronzePackageCosts = new int[1000];
subsBronzePackageCosts[0] = 600;
subsBronzePackageCosts[1] = 500;
subsBronzePackageCosts[2] = 400;
subsBronzePackageCosts[3] = 300;
I'm trying to loop through said array so that for example, a user has set the duration as 3, it'll iterate using the for loop through my array and set subscriptionCost to the appropriate value. In this instance, that being 400.
The part I'm stuck with, is iterating through the array with the for loop. I have it so it's only adding + 1 and reporting 500 every time. I did have a solution working for if else statements for each different package type and duration, but obviously, this isn't ideal practice and causes repetitive code, which I'm trying to avoid.
Thanks in advance!
EDIT: To add a bit more context. I have three tiers of subscriptionPackage to work with: Bronze, Silver and Gold.
All of these packages have different pricings and the pricings change with the length of subscriptionDuration that the user enters.
The packages/pricings are:
Bronze prices are 600 for 1 month, 500 for 3 months, 400 for 6 months and 300 for 12 months.
Silver prices are 800 for 1 month, 700 for 3 months, 600 for 6 months and 500 for 12 months.
Gold prices are 999 for 1 month, 899 for 3 months, 799 for 6 months and 699 for 12 months.
Your code here is a bit of a mess to look at. But I guess I would point you to the logic in your if statement ...
subscriptionPackage.equals(subscriptionPackage) ... this is always true, right? So you can just delete this.
subscriptionDuraction == suscriptionDuration ... thius is also always true, right? So your whole if statement disappears.
So this if statement ALWAYS evaluates to true, which means you will always hit the return statement in the if block, with i=1, and in your array, [1] = 500.
I would suggest attempting to work with classes, for example:
// Going this far could be up for debate
public enum SubscriptionType { GOLD, SILVER, BRONZE }
public enum SubscriptionDuration { MONTHLY, QUARTERLY, BI_ANNUALLY, ANNUALLY }
public class SubscriptionFee {
SubscriptionType type; // Replace with String
SubscriptionDuration duration; // Replace with Integer
int cost;
}
Both type and duration are up for debate if you'd rather use String and Integer respectively.
You can try to implement these in your current code and see if it's easier to loop through all the options comparing:
subscriptionFee.type
subscriptionFee.duration
to the information you've collected from the "user".
Related
I have two vectors, vectorName and vectorNum, I need to iterate over them asking for input up to ten times or until nothing is entered, the problem is that when I reach the 10th loop it asks for vectorName an 11th time and then throws IndexOutOfBoundsException
this is my code:
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int nameQuantity = 0;
int numQuantity = 0;
String vectorName[] = new String[10];
int vectorNum[] = new int[10];
System.out.println("enter name or enter nothing to end");
vectorName[nameQuantity] = read.nextLine();
if (vectorName[nameQuantity].length()==0) {
System.out.println("end");
}else {
nameQuantity++;
while(nameQuantity<11) {
System.out.println("enter a number from 1 to 12");
int num = read.nextInt();
if (num<=12 && num>=1) {
vectorNum[numQuantity] = num;
numQuantity++;
System.out.println("enter name or enter nothing to end");
read.nextLine();
vectorName[nameQuantity] = read.nextLine();
if(vectorName[nameQuantity].length() == 0 || numQuantity == 10) {
for (int n = 0; n<=numQuantity-1; n++) {
System.out.print("\n " + vectorName[n] + " "+ vectorNum[n]);
}
nameQuantity = 11;
}else {
nameQuantity++;
}
}else {
System.out.println("number must be from 1 to 12");
}
}
}
}
}
I tried changing the vector size to 11 which worked but as a result it saves an 11th name which I don't need since I expect it to ask only up to ten times the names and numbers.
I also tried changing the do while to a while, the same thing happens.
Start of 1st Iteration:
nameQuantity = 1
numQuantity = 0
Start of 2nd Iteration:
nameQuantity = 2
numQuantity = 1
...
Start of 10th Iteration:
nameQuantity = 10
numQuantity = 9
Calling vectorName[nameQuantity] will cause the IndexOutOfBoundsException at this point, since vectorName has a size of 10, meaning the last index is 9.
I'm not sure why you're asking for the user to enter a name, then starting a loop where you ask for a number and then ask for a name.
Your logic:
Receive name from user
If name is empty
Stop
Else
Loop 10 times:
Receive number from user
If name is empty or received 10 numbers
Stop
Why not just have everything in a loop where you ask for a name first, and if a name was provided, ask for a number?
Loop 10 times
Receive name from user
If name is empty
Stop
Else
Receive number from user
I have an assignment where I need to do certain calculations in separate methods using data entered by the user. My problem is with the user input. It is supposed to be done with a separate method (I do not think I am allowed to use arrays for storing the inputs). The user should be able to enter as many values they want and then exit with "q". The program should then take the first two numbers, calculate e.g. an area and volume with those (with other methods I did not include here), present the result, take the next two numbers the user entered, calculate and present results. This should be repeated until it reaches the "q" value. So for example:
Enter your values: 9 5 3 7 q
radius: 9 height: 5
Area = 254
Volume = 424
radius: 3 height: 7
Area = 28
Volume = 65
A problem I am having is that only the first value is assigned to a variable and then the user has to enter data again for the next variable, even though there's still more numbers left from the first time.
import java.util.Scanner;
public class Stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int radie, height;
radie = userInput("");
height = userInput("");
}
public static int userInput(String message) {
int number = Integer.MAX_VALUE;
while (number == Integer.MAX_VALUE) {
System.out.print(message);
if (input.hasNextInt()) {
number = input.nextInt();
}
input.nextLine();
}
return number;
}
}
I understand there are massive flaws in my code here, I'm very lost and not sure where to even start with solving the problem. Any help or tips are very welcome! Thanks in advance!
Did you read 'Scanner.hasNextInt()' method documentation?
There is written:
Returns:
true if and only if this scanner's next token is a valid int value
So question if
number == Integer.MAX_VALUE
doesn't make sens.
Try to ask if hasNextInt()
returns true or false
Edit: Also
Why do you assume that after number is always 'q'?
Change condition in while statement
Don't really understand your mean, but i did some changes:
import java.util.Scanner;
public class stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
userInput();
}
public static void userInput() {
while (true) {
System.out.println("Enter your values:");
String message = input.nextLine();
//Split data with space
String[] data = message.split(" ");
int pointer = 2;
for (String i : data) {
if (i.equals("q")) {
System.out.println("Stopped.");
System.exit(0);
}
if (pointer % 2 == 0) {
System.out.println("radius: " + i);
}
if (pointer % 2 == 1) {
System.out.println("height: " + i);
}
pointer++;
}
}
}
}
Affect:
Enter your values:
1 2 3 4 5 6 7 8
radius: 1
height: 2
radius: 3
height: 4
radius: 5
height: 6
radius: 7
height: 8
Enter your values:
1 q
radius: 1
Stopped.
Process finished with exit code 0
Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number
Can anyone help me here?? I have compiled and successfully run a program using Java which takes user inputs from an "inputdialog" box and displays this information back in the console along with a simple mathematical formula. The problem I cannot seem to overcome is when the data is input the user has an option to enter another set of the same data type but I need the console to register this as a second input. This is how far I am currently with the section of code and my ideas on how to make this work using an array but I have been informed that saving/storing the data as an object might be a better option?
private void enterCar()
{
String carInfo;
int carHours;
int i = 0;
int[] carNumb = new int[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car "+carNumb+" entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carNum == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
When I compile and run the console I get the line "Details for car [I#6659c656 entered". This line does change to something like "[I#7665c575" the next time I activate the option so I can assume that I may need to assign a value to the number differently?
I have tried the option that is show in the code provided as well as trying to activate a list using (1, 2, 3, ect) but this also just outputs that random line of numbers and letters.
I guess to simplify my question. I need to store 20 individual inputs from an 'InputDialog' box and store it for later access in a console.
I need to store 20 individual inputs from an InputDialog box and store it for later access in a console.
Use a loop such as for.
That information then gets stored as "Details for car 1 entered:" and then the information displayed.
As I said before, you should use index of array instead of array. And because array is zero-based index, so I use carNumb[i] + 1 to print out the order.
Then calculate fee and store to carNumb array.
Note that, your fee is double type => carNumb should be double type to store correct value.
Full code:
public void enterCar() {
String carInfo;
int carHours;
int i = 0;
double[] carNumb = new double[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
for (; i < carNumb.length; i++) {
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car " + (carNumb[i] + 1) + " entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf("" + carInfo + " " + carHours + " $");
carNumb[i] = getFee(fee, carHours);
System.out.printf("%3.2f", carNumb[i]);
System.out.printf("\n\n");
}
}
private double getFee(double fee, int hours) {
if (hours == 1) {
return fee;
}
if (hours == 2) {
return fee + 4.5;
}
if (hours >= 3) {
return 3 + hours * 4.5;
}
return 0;
}
Did I get your idea?
My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)