Calculating totalCost - subtotal

Ok below is my code for a class I am taking... I need to know how to properly code the totalCost for this product and I can not for the life of me figure out how to properly do this. The price per product is $1 and I need to calculate a 7% sales tax as well. Help!!!
import javax.swing.JOptionPane;
/**
* #author bary
*/
public class CocaCola1 {
public static void main(String[] args)
{
String openingMsg = "*** Welcome to CocaCola Online Ordering System ***\n"
+ "Do yourself a favor and order some Cola... NOW!";
JOptionPane.showMessageDialog(null, openingMsg);
System.out.println(0);
String name = getUserInput("What is your name?");
System.out.println(name);
String returnCustomer = getUserInput("Are you a returning customer? (yes/no)");
System.out.println(returnCustomer);
String orderType = getUserInput("Would you like to purchase Dasani, Coke, Diet Coke, or Cherry Coke?");
System.out.println(orderType);
String orderAmount = getUserInput("How many units would you like to purchase?");
System.out.println(orderAmount);
Integer.parseInt(orderAmount);
// each unit costs $1.00 so orderAmount is equal to cost per unit
double salesTax = 0.7;
// create and display output string
String outputMsg
= "Hello " + name + ".\n\n" +
"Your return customer status is " + returnCustomer + ".\n" +
"You ordered " + orderAmount +
" units of " + orderType + ".\n" +
"Your total cost is $" + orderAmount + salesTax + ".\n" +
"Thank you for visiting CocaCola" + ".\n\n" +
"Your order will be proccessed ASAP.\n";
JOptionPane.showMessageDialog(null, outputMsg);
}
private static String getUserInput(String prompt)
{
int failCount = 0;
do
{
String answer = JOptionPane.showInputDialog(prompt);
if (answer == null)
{
System.exit(0);
}
answer = answer.trim();
if (answer.isEmpty())
{
JOptionPane.showMessageDialog(null, "You must provide a non-blank answer");
failCount = failCount + 1;
} else
{
return answer;
}
} while (failCount < 3);
JOptionPane.showMessageDialog(null, "You failed three times to provide input... Try again later!");
System.exit(0);
return null; // means nothing, as I just exited on the prior line, but need it to compile
} // end main()
} // end class CocaCola1

orderAmount + salesTax would only be if the sales tax was static. You need to multiply the orderAmount by the sales tax and add salestax
ex: orderAmount*salesTax+prderAmount
or set salesTax to 1.7 and it would be
orderAmount*salesTax

Related

Error: no suitable method found for length(int)

First time posting a question. Maybe I'm just being an idiot that's not seeing the problem, but can anyone identify what's wrong with my code below? Everything else works fine. But when the code is done compiling, it says "Error: no suitable method found for length(int)" for if (l.length(0)) and if (f.length(0)).
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int salary;
double savingsRate;
double interestRate;
int employmentYears;
double retirementSavings;
System.out.println("Enter input salary savings_rate interest_rate years_employed lastname firstname");
salary = scnr.nextInt();
savingsRate = scnr.nextDouble();
interestRate = scnr.nextDouble();
employmentYears = scnr.nextInt();
String l = scnr.nextLine(); // Last Name
String f = scnr.nextLine(); // First Name
retirementSavings = employmentYears * savingsRate * salary * (1 + interestRate);
if (salary < 0) {
System.out.println("Salary is negative");
}
else if (salary > 1000000) {
System.out.println("Error: Salary " + salary + "exceeds maximum 1000000.0");
}
else {
System.out.println("Salary: " + salary);
}
if (savingsRate < 0) {
System.out.println("Savings rate is negative");
}
else if (savingsRate > 0.5) {
System.out.println("Error: Savings rate " + savingsRate + "exceeds maximum 0.5");
}
else {
System.out.println("Savings Rate:" + savingsRate);
}
if (interestRate < 0) {
System.out.println("Interest Rate is negative");
}
else if (interestRate > 0.25) {
System.out.println("Error: Interest Rate " + interestRate + "exceeds maximum 0.25");
}
else {
System.out.println("Interest Rate: " + interestRate);
}
if (employmentYears < 0) {
System.out.println("Years employed is negative!");
}
else if (employmentYears > 50) {
System.out.println("Error: Years employed " + employmentYears + "exceeds maximum 50");
}
else {
System.out.println("Years of Employment: " + employmentYears);
}
if (l.length(0)) {
System.out.println("Error: Name too short");
}
else if (l == f) {
System.out.println("Error: Last Name and First Name are the same");
}
else {
System.out.println("Last Name: " + l);
}
if (f.length(0)) {
System.out.println("Error: Name too short");
}
else {
System.out.println("First Name: " + f);
}
System.out.println("Retirement Savings: " + retirementSavings);
}
}
I think you are trying to check if the name is empty, Am I right?
you have:
1) string.length() : length() method is a final variable which is applicable for string objects. length() method returns the number of characters presents in the string.
2) array.length : length is a final variable applicable for arrays. With the help of length variable, we can obtain the size of the array.
(visit geeksforgeeks to see more).
But you don't have a String.length(int) method.

I have this array class that is not removing items after re-running my recyclerview

The below class is used in an array.
package com.example.ShivitoMGO;
public class RoomTable {
public String RoomName,UpDown,minmaxint;
}
Main Activity
static ArrayList <RoomTable> CountCheck = new ArrayList<>();
public void playerup(View vvv){
st_spinner = v1.findViewById(R.id.spinner);
st_reportLayout = v1.findViewById(R.id.reportlayout);
st_Leanervidimg = v1.findViewById(R.id.Linearvidcopy);
TextView roomname = v1.findViewById(R.id.action_Players1);
RoomTable roomtb = new RoomTable();
if (CountCheck.size() == 0){
//playerupdown = "up";
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ",roomtb.RoomName+ " " + roomtb.minmaxint +" " +roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
Log.d("Longclickhere: ", mRoomSize.get(position1));
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(0).RoomName));
}else {
int exist1 = 0;
int poss;
for (int i = 0; i < CountCheck.size(); i++) {
if (roomname.getText() == CountCheck.get(i).RoomName) {
Log.d("RoomNametxt: " , CountCheck.get(i).RoomName);
Log.d("RoomNametxt: ", (String) roomname.getText());
Toast.makeText(this, "Notification " + CountCheck.get(i).RoomName + " OFF!", Toast.LENGTH_LONG).show();
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
CountCheck.remove(i);
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
st_reportLayout.setVisibility(View.GONE);
exist1 = 1;
poss = i;
} else {
exist1 = 0;
}
}
if (exist1 == 0) {
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ", roomtb.RoomName + " " + roomtb.minmaxint + " " + roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
}
Log.d("CountSize: ", String.valueOf(CountCheck.size()));
for (int xb = 0;xb<CountCheck.size();xb++) {
try {
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(xb).RoomName));
} catch (Exception e) {
Log.d("Out of range ", String.valueOf(e));
}
}
}
}
Recycler-View
#Override
public boolean onLongClick(View v) {
// Launch your web intent
if (CountCheck.size() != 0){
Log.d("Longclickhere: ",mRoomSize.get(position));
Toast.makeText(mContext, mRoomSize.get(position), Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, "Will notify when "+mRooms.get(position)+" players decrease", Toast.LENGTH_SHORT).show();
String[] minmaxval = mRoomSize.get(position).split("/");
MainActivity.CountCheckint = Integer.parseInt(minmaxval[0].trim());
} else{
//MainActivity.CountCheck = "";
Toast.makeText(mContext, "Player Decrease notification OFF", Toast.LENGTH_SHORT).show();
}
return true;
In this app the recycler view creates the "rooms" and if the room is selected the textview and 2 other values are put in to the RoomTable. these are stored and used in a service to check if ether of the other to values change. Everything works as intended unless i use the swip-to-refresh witch runs the recycler-view again. If i do not refresh and i select the same item in the recycler-view it will remove it from CountCheck . However if i run the refresh and select the same recycler-view item that i selected previously it will add it instead of removing it. This Makes no since to me because i use a for loop to Check the CountCheck.get(i).RoomName aka the textview and if the names are the same then my if statement will remove instead of add. is it somehow possible i'm ending up with 2 CountCheck Objects????? with the same name???? Please I'm out of ideas on this one. Thanks.
I dont remember why. Maybe someone can explain but i changed this line
if (roomname.getText() == CountCheck.get(i).RoomName)
To this
if (roomname.getText().equals(CountCheck.get(i).RoomName));
and that fixed the issue. please let me know the difference if you are reading this.

Accessing Current SharedPreferences Data from Background Services

My app uses a countdown timer in the background in a class that extends Services. The background running service is designed to access the Sharedpreferences data of the app. During the countdown, a particular integer in the Sharedpreferences changes value and the updated value is expected to be accessed in the onFinish() call of the countdown timer. The problem now is that the Service don't read the updated valued from the Sharedpreferences but rather returns the initial value at the point the background service started.
I saw somewhere that the solution to the problem is to use
PreferenceManager.getDefaultSharedPreferences()
instead of getSharedPrefences to be able access the current SharedPreferences value. I implemented this recommendation but the problem persist.
Please somebody should help me out because trying to figure out this is taking too much of my time.
My code is here:
public class BroadcastService extends Service {
DatabaseHelperClass myDatabase = new DatabaseHelperClass(this);
private SharedPreferences defaultSharedPreferences, sharedPreferences, staffSignedIn;
private SharedPreferences.Editor staffEditor, defaultSharedPreferencesEditor;
int countSignIn;
private SimpleDateFormat simpleDateFormatII;
Long timeLeftInMiliseconds;
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.cenitscitech.www.etimebook.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
defaultSharedPreferencesEditor = defaultSharedPreferences.edit();
sharedPreferences = getSharedPreferences("setTime", MODE_PRIVATE);
//staffSignedIn = getSharedPreferences("present", MODE_PRIVATE);
//countSignIn = staffSignedIn.getInt("max", 0);
//staffEditor = staffSignedIn.edit();
simpleDateFormatII = new SimpleDateFormat("MMM EEE dd, yyyy HH:mm");
Log.i(TAG, "Starting timer in broadcast receiver...");
Log.i(TAG, "max Count Obtained onBroadcastCreate: "+defaultSharedPreferences.getInt("max", 0));
}
#Override
public void onDestroy() {
//cdt.cancel();
Log.i(TAG, "Timer in broadcast receiver cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timeLeftInMiliseconds = intent.getLongExtra("timeLeft", 0L);
cdt = new CountDownTimer(timeLeftInMiliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
SharedPreferences defaultShared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
/*bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);*/
}
#Override
public void onFinish() {
SharedPreferences defaultSharedPreferences2 = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
countSignIn = defaultSharedPreferences2.getInt("max", 0);
Log.i(TAG, "Timer finished");
bi.putExtra("countdown", "Timer finished");
sendBroadcast(bi);
StringBuilder phoneBuilder = new StringBuilder();
Calendar cStart = Calendar.getInstance();
cStart.set(Calendar.HOUR_OF_DAY, 0);
cStart.set(Calendar.MINUTE, 0);
cStart.set(Calendar.SECOND, 0);
Long cStartLong = cStart.getTimeInMillis();
Calendar cEnd = Calendar.getInstance();
cEnd.set(Calendar.HOUR_OF_DAY, 23);
cEnd.set(Calendar.MINUTE, 59);
cEnd.set(Calendar.SECOND, 59);
Long cEndLong = cEnd.getTimeInMillis();
String[] conditionsElements;
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + defaultSharedPreferences2.getInt("max", 0));
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + countSignIn);
if (defaultSharedPreferences2.getInt("max", 0) > 0) {
Log.i(TAG + " onFinish", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[defaultSharedPreferences2.getInt("max", 0)];
for (int i = 1; i <= defaultSharedPreferences2.getInt("max", 0); i++) {
conditionsElements[i - 1] = defaultSharedPreferences2.getString(Integer.toString(i), "NoElement");
Log.i(TAG + " onFinish", "conditionsElement[" + (i - 1) + "] = " + defaultSharedPreferences2.getString(Integer.toString(i), "NoElement"));
if (i < defaultSharedPreferences2.getInt("max", 0)) {
phoneBuilder.append("MOBILE_NUMBER = ? OR ");
Log.i(TAG + " onFinish", "phoneBuilder[" + (i - 1) + "]: " + phoneBuilder);
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff")+"_");
} else if (i == defaultSharedPreferences2.getInt("max", 0)) {
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff"));
phoneBuilder.append("MOBILE_NUMBER = ?");
Log.i(TAG + " onFinish", "phoneBuilder[final]: " + phoneBuilder);
}
}
} else {
Log.i(TAG + " onFinishInsideElse", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[1];
conditionsElements[0] = "NoElement";
phoneBuilder.append("MOBILE_NUMBER = ?");
}
Cursor cursor = myDatabase.queryAbsentStaff(SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
phoneBuilder.toString(),
conditionsElements);
Log.i(TAG + " onFinish", "\n" + "SET TIMES:" + "\n" + cStartLong + "\n" + cEndLong + "\n" + "RETURNED ROWS:" + "\n" + cursor.getCount());
/*staffEditor.putInt("max", 0);
staffEditor.apply();
for(int i=0; i<staffSignedIn.getInt("totalStaff", 100); i++){
staffEditor.putString(Integer.toString((i+1)), "empty").apply();
}*/
if(cursor.moveToFirst()){
for (int i = 0; i < cursor.getCount(); i++) {
if(myDatabase.insertTimeBookRecord(cursor.getString(cursor.getColumnIndex(SURNAME_COLUMN)), cursor.getString(cursor.getColumnIndex(FIRST_NAME_COLUMN)),
cursor.getString(cursor.getColumnIndex(MIDDLE_NAME_COLUMN)), cursor.getString(cursor.getColumnIndex(MOBILE_NUMBER_COLUMN)),
"ABSENT", Long.toString(System.currentTimeMillis()), 1000000L, "NO", "0000", System.currentTimeMillis(), "notSynced", "notSynced")){
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}else{
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}
}
}
Log.i(TAG +" onFinish: ", "max val reset: "+defaultSharedPreferences2.getInt("max", 0));

Changing the constraints in a Container object

In Java 8, the Container class has an void add(Component comp, Object constraints) method that adds the component with a constraints information. I want to build a GUI with three panels, where pressing a button would result in switching the constraint information of the components that do not include the button object. How is it possible to switch the constraint information?
EDIT:
I tried the following:
private Map<SpecUITitlePanel, GridBagConstraints> constraints = new Hashtable<SpecUITitlePanel, GridBagConstraints>();
[…]
switchPanelsButton.setText( "Switch panels");
switchPanelsButton.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed( final java.awt.event.ActionEvent event) {
switchPanelsActionPerformed( event);
}
[…]
private void switchPanelsActionPerformed( final java.awt.event.ActionEvent event) {
boolean swapped = false;
final GridBagLayout layout = (GridBagLayout) getLayout();
final Iterator<SpecUITitlePanel> keysIter = constraints.keySet().iterator();
// summaryPanel, testPanel
while (keysIter.hasNext() && layout != null) {
final SpecUITitlePanel key = keysIter.next();
final String title = key.getTitle();
final Iterator<SpecUITitlePanel> keysIter2 = constraints.keySet().iterator();
while (keysIter2.hasNext()) {
final SpecUITitlePanel key2 = keysIter2.next();
final String title2 = key2.getTitle();
if (!title.equals( title2)) {
if (!title.contains( BUTTON_PANEL_TITLE) && !title2.contains( BUTTON_PANEL_TITLE)) {
// swap components
String message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
final GridBagConstraints value = constraints.get( key);
final GridBagConstraints value2 = constraints.get( key2);
constraints.put(key, value2);
layout.setConstraints( key, value2);
constraints.put(key2, value);
layout.setConstraints( key2, value);
swapped = true;
message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
}
}
}
}
if (swapped) {
repaint();
}
}
The relevant part of the output is
component = Test, java.awt.GridBagConstraints#5179288b; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#f1a7ed2
component = Test, java.awt.GridBagConstraints#f1a7ed2; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#5179288b

How do I make so that when I input a value into a scanner if it is not an integer it won't give me an error?

I am writing a program that does simple math problems. What I am trying to do is to make it so that even if I input a string into the the scanner level it will not give me an error. The level is to choose the difficulty of the math problems. I have tried parseInt, but am at a loss of what to do now.
import java.util.Random;
import java.util.Scanner;
public class Test {
static Scanner keyboard = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
String level = intro();//This method intorduces the program,
questions(level);//This does the actual computation.
}
public static String intro() {
System.out.println("HI - I am your friendly arithmetic tutor.");
System.out.print("What is your name? ");
String name = keyboard.nextLine();
System.out.print("What level do you choose? ");
String level = keyboard.nextLine();
System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + ".");
System.out.println("Good luck.");
return level;
}
public static void questions(String level) {
int value = 0, random1 = 0, random2 = 0;
int r = 0, score = 0;
int x = Integer.parseInt("level");
if (x==1) {
r = 4;
}
else if(x==2) {
r = 9;
}
else if(x==3) {
r = 50;
}
for (int i = 0; i<10; i++) {
random1 = generator.nextInt(r);//first random number.
random2 = generator.nextInt(r);//second random number.
System.out.print(random1 + " + " + random2 + " = ");
int ans = keyboard.nextInt();
if((random1 + random2)== ans) {
System.out.println("Your answer is correct!");
score+=1;
}
else if ((random1 + random2)!= ans) {
System.out.println("Your answer is wrong!");
}
}
if (score==10 || score==9) {
if (score==10 && x == 3) {
System.out.println("This system is of no further use.");
}
else {
System.out.println("Choose a higher difficulty");
}
System.out.println("You got " + score + " out or 10");
}
else if (score<=8 && score>=6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Do the test again");
}
else if (score>6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Come back for extra lessons");
}
}
}
The first error I see is that you tried to Integer.parseInt() a String "level" instead of the String variable named level
int x = Integer.parseInt("level");
should be
int x = Integer.parseInt(level);
Also, when defining level you can use keyboard.nextInt instead of keyboard.nextLine
String level = keyboard.nextInt();
Then, you wouldn't have to do an Integer.parseInt() operation later on

Resources