Please be gentle as this is my first programming class and my first time ever doing something like this.
I'm tasked with creating a java program (only my second week of this class) with creating a cell phone plan based off of the mins a user puts in.
Basic Talk is 400 mins, $30 and 0.35 per min over.
Standard Talk is 600 min, for $40 and 0.30 per min over.
Unlimited is anything over 600 mins for $60 per min.
The issue I'm having is the math portion of this. No matter what I put in for the number of mins, it always returns the same dollar amount to pay, which is $140.
I have tried all various types of suggestions on the web, with the same result.
My code might be messy and I do apologize, as I said, I've been trying a variety of different things and said I would go back and clean it up some when I got this working correctly.
I need to show the amount of min entered by the user, then show them the best plan based off the mins they entred and how much they can expect to pay.
Any help would be greatly appreciated. I've been racking my brains for 3 days now and it's due by midnight Monday.
import java.util.Scanner;
import java.util.Formatter;
public class Java_Lab_2 {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// Different Talk Plans
final double basicTalk = 30.00;
final double standardTalk = 40.00;
final double unlimtedTalk = 60.00;
final double basicextramin = 0.35;
final double standardextramin = 0.30;
// Minutes per plan
int basicMinutes;
basicMinutes = 400;
int standardMinutes;
standardMinutes = 600;
String unlimitedMinutes = "unlimited";
// Extra Charge per min per plan
String unlimited = "included";
//Number of minutes Basic
int numberOfMins = 0;
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
// Get number of minutes spent
System.out.println("How many talk minutes do you use per month?");
numberOfMins = scan.nextInt();
// Best Plan
if (numberOfMins <= 400) {
System.out.println("The best plan (s) for you is Basic Talk ");
System.out.println("Expect to pay $" + basicTalk);}
if ((numberOfMins > 401) &&(numberOfMins <428)) {
System.out.println("The best plan (s) for you is Basic Talk");
System.out.format("Expect to pay $%-5.2f", + extraMinCharge);
There is an order issue in your code: you do
int numberOfMins = 0;
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
You need to reorder this so that you have something like
System.out.println("How many talk minutes do you use per month?");
int numberOfMins = scan.nextInt();
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
So that you are not calculating with number of minutes set first, otherwise you are calculating with number of minutes set to 0.
Related
Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.
I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));
I'm playing around with Java for the first time and an error is appearing. I don't understand why.
The error is:
java.util.InputMismatchException
It says that the problem is in line 20 ("price = in.nextDouble();"), but I can't understand the problem.
It looks like that the problem happens after I insert the number of days, the cost per day and I used decimal, I put for example 34.98. Isn't the point of using double to be able to use decimal numbers?
Here is the code:
int days;
double price;
System.out.println("How many days you will be here?");
Scanner in = new Scanner(System.in);
days = in.nextInt();
System.out.println("How much you can afoord per day?");
price = in.nextDouble();
double total = price * days;
System.out.println("Youll be paying "+ total);
This code works fine for me
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
int days;
double price;
System.out.println("How many days you will be here?");
Scanner in = new Scanner(System.in);
days = in.nextInt();
System.out.println("How much you can afoord per day?");
price = in.nextDouble();
double total = price * days;
System.out.println("Youll be paying "+ total);
}
}
Output
Executing Build Command: javac /root/HelloWorld.java
How many days you will be here?
3
How much you can afoord per day?
34.98
Youll be paying 104.94
Process exited successfully
So i found the problem, i had to add after Scanner... "in.useLocale(Locale.US);"
That is why it got this error.
I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));
I have been fighting with this for quite some time and have found a couple useful resources, yet the problem persists.
Here's my code:
import java.util.Scanner;
public class Stocks {
public static void main(String [] args){
// value of stock at beginning of year and end of year.
final int beginningStock = 10;
final int endStock = 20;
// value of stocks by quarter; there are three quarters.
int firstQuarter;
int secondQuarter;
int thirdQuarter;
String broker;
String Buy;
firstQuarter = 10;
secondQuarter = 30;
thirdQuarter = 20;
//Tell client the maximum value/price of the stock during the year.
System.out.println("The maximum price of a stock share in the year is: $" + secondQuarter + ".");
// Tell client the minimum value/price of the stock during the year.
System.out.println("The minimum price of a stock share in the year is: $" + firstQuarter + ".");
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
}
else if (broker == "Sell"){
//Calculate change relative to end of year
double endIncrease;
endIncrease = (double)(endStock - beginningStock)/(endStock);
//Convert decimal to percentage and tell client percentage increase relative to end of year.
System.out.println("The percentage increase of the stock through the year, relative to end of year, is: %"+ ((int)(endIncrease*100))+ "." );
}
}
}
The issue I am having is around line 29:
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
It will take the String but will not use it. I don't know what I am doing wrong. Forgive me this is my first post on here.
The problem is that == tests for reference-equality rather than value-equality; that is, it checks that the two sides are the same object, rather than equivalent objects. You need to change this:
if (broker == "Buy"){
to this:
if (broker.equals("Buy")){
Use equals() instead of == to compare strings.
== is the identity comparison operator, not equivalence.
As others said, you should use equals() to compare instances of String.
You have another problem in your code. You're using Scanner´s method next(String pattern), which will return a String if it matches the passed pattern. Since you're passing an empty Stringas the pattern it will raise an exception. You should be using next() instead.
"Buy".equals(broker) should be condition check
In Java string comparison should be .equals not ==