How to obtain and utilize next String in Java - java

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 ==

Related

Pizza price calculating using 'if' statements in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I've tried to make Java code to communicate with the user.
The code is about calculating a pizza price assuming the pizza price is a final int and doesn't change.
The only thing that affects the price is the add-on that the customer wants on the pizza (tomato, mushrooms, cheddar cheese).
I've tried to create code that covers every option the customer picks using 'if' statements,
but I think there is easier way to do it.
(I want the program to calculate the price given only the add-on name.)
For example, the customer picks Mushroom and Tomato so the pizza price will be the pizza price + tomato price + mushroom price.
Is there any easier way to solve it?
Or should I cover every option the customer picks with if/else statements?
public static void main(String[] args){
Scanner s= new Scanner(System.in);
final int pizzaPrice= 12;
int Mushrooms = 2;
int Tomato= 2;
int Corn = 2;
int Olives = 2;
int CheddarCheese=3;
int bulgaritCheese=3;
int yellowCheese= 3;
String cheapAddOns ="Mushrooms , Tomato, Corn, Olives";
String expensiveAddOns = "Cheddar cheese , Bulgarit cheese , Yellow cheese";
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
cheapAddOns=s.next();
System.out.println("Please enter second AddOns (Cheddar cheese , Bulgarit cheese ,Yellow cheese)");
expensiveAddOns=s.next();
if( cheapAddOns== "Mushrooms" || expensiveAddOns=="Cheddar cheese" ) {
System.out.println("Your Pizza price is: $" + pizzaPrice + Mushrooms + CheddarCheese );
}
else if (cheapAddOns=="Tomato" || expensiveAddOns=="Bulgarit cheese") {
System.out.println("Your Pizza price is: $" +pizzaPrice+ Tomato + bulgaritCheese);
}
}
First of all when you name your variables, don't start with a capital letter
int mushrooms, not int Mushrooms.
Second thing, when you compare Strings == operator will not work. you must use stringName.equals(). In your case it would look like:
cheapAddOns = s.next();
if(cheapAddOns.equals("tomato") || cheapAddOns.equals("mushrooms") || ...){
//this way you can get one if for all cheap addons;
pizzaPrice += 2; //read below to undrstand why i would add price this way
}
And the same check for expensive addons.
What you do when you initiate cheapAddOns and expensiveAddOns is incorrect, I mean that you initiate them with start variable, and next you read them from standard input. Initiate them with no value:
String cheapAddOns;
String expensiveAddOns;
And for this example, you dont have to use final int, better initiate it as an normal integer, and if any statment is true, add to this value. It would look like this:
int pizzaPrice = 12;
int cheapAddonPrice = 2;
int expensiveAddonPrice = 3;
if(anyStatement){
pizzaPrice += 2; //2 for cheap, 3 for expensiv addon
}
System.out.println("Your pizza costs: $" + pizzaPrice)
It works only when all cheap addons cost $2 and all expensive addons cost $3. If each addon has another price, you will need more if statements to calculate price.
But calculate price in as many statements as you want and print it once (until you print only price (without addons list).
You made a lot of simple mistakes here so i think that you just start your programming adventure. Don't learn bad habbits, try to imporove your code with each day.
if all cheap add-ons have the same price, one way could be:
String cheapAddOns = "Mushrooms, Tomato, ...";
int cheapPrices = 2;
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
String cheap = s.next();
int price = pizzaPrice;
if ( cheapAddOns.indexOf(cheap) >= 0 ) {
price += cheapPrice;
}
then repeat the code using expensiveAddOns.
Note that you will need to consume the CR before calling s.next() to get the user's next input.

New to Java Programming, having math coding issues

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.

Invalid Character Constant in Java?

Here is my code:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound
{
public static void main(String[] args)
{
String input;
char timeTraveled;
Scanner keyboard = new Scanner(System.in);
double distance;
double time;
double time2;
double time3;
time = (distance/ 1100);
time2 = (distance/ 4900);
time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
input = keyboard.nextLine();
System.out.print("Enter distance: ");
distance = keyboard.nextDouble();
switch(timeTraveled)
{
case 'air':
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = input.charAt(0);
break;
keyboard.close();
}
} // main()
} // class SpeedOfSound
Why is case 'air': giving me the error invalid character constant twice? My professor has a different example for a different program and it's almost the same as what I'm doing but he doesn't get the error. Why do I get this error?
You've got several problems here.
First, single quotes are reserved for single characters, like 'a'. Whole strings need to be placed in double quotes.
Second, timeTraveled is never assigned anything anyway by the time you use it, so it "might" not have been initialized by the time you try to run it (and get things to compile). You probably want to use input instead.
This is to say, as long as you're using Java 7 or newer, you should write this as your switch argument:
switch(input) {
// statements to follow
}
I'm not sure what that assignment at the end of your "steel" case is meant to do, but you may want to move its logic out of the switch statement entirely.
In some programming languages, single quotes (') and double quotes (") are interchangeable. In Java (and also in C and C++), they are not.
If you want to specify a multi-character string literal, use double quotes: "air".
Additionally, it is not clear what do expect to happen when you compare a char (timeTraveled) to a string ("air").
I dont understand the logic of this program. If U need to enter the word and then do something depending on it try to make something like
String timeTraveled;
if (timeTraveled.equals("air")){
//do something
} else if (timeTraveled.equals("water")) {
//do something
} ...
I found multiple issue in your code:
It should be "air" not 'air' (solution for your op).
Datatype of timeTraveled is char but you are trying to match it with String (like "air", "water", etc.).
timeTraveled is not initialized.
distance is not initialized while doing calculation for time, time1 & time2.
keyboard.close(); is unreachable code. Move it outside the switch block or add it in default case.
Ideally, you should be using chars in your switch case or create enum for better clarity.
#justaregularguy - You are getting this error because you have taken air as a character.
mention air as String and you will be fine.
This will help you to - in case you will try non permitted values.
"Cannot switch on a value of type Float. Only convertible int values, strings or enum variables are permitted"
'air' is using single quotes. Single quotes denote a character constant. What you're looking for is "air", a String constant.
You seem to be a new programmer. I made some improvements to your program, and I'll show you them here:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound {
public static void main(String[] args) {
char timeTraveled; //what is this even doing here?
Scanner scanner = new Scanner(System.in);
double time = (distance/ 1100);
double time2 = (distance/ 4900);
double time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
String material = scanner.nextLine();
System.out.print("Enter distance: ");
double distance = scanner.nextDouble();
switch (material) {
case "air":
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = material.charAt(0); //what is this even doing here?
break;
}
scanner.close();
} // main()
} // class SpeedOfSound
Made the spacing and indenting more consistent
Renamed your Scanner object. "keyboard" is not an appropriate name for a Scanner object, since scanner works with not only keyboard input, but also string and file input.
I combined the declaration of your "time" variables and the definition
E.g.
double time; //a declaration of "time"
time = (distance/ 1100); //a definition of "time"
//becomes:
double time = (distance/ 1100); //a declaration AND definition of "time"
changed 'air' to "air"", also, changed the switch case variable to "material" (which used to be called "input", and is the string that holds the user's input), rather than it using timeTraveled (some miscellaneous character?)
Since your program is only going to be displaying one time of the three possibilities, why calculate all 3? I suggest you rework your algorithm as follows:
Ask the user for the material and distance they want. Set a variable "speed" equal to 1100, 4900, or 16400 depending on the user's choice of air, water or steel. Then, calculate time as distance / speed.
This saves you from repeating 3 identical System.out.println() statements, saves you from having 3 time variables (when you only need 1),

Can't understand this scanner or addition command

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));

giveChange method computes change and number of coins to return java?? [duplicate]

This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.

Categories