Ending a Loop only after a user input gives a yes - Java - java

I am trying to create an app to take orders for a Hamburger and add additions. I want the additions to the burger to be based on a scanner input, but I am getting the error "Exception in thread "main" java.util.NoSuchElementException: No line found". Would appreciate if someone could help me understand where am I going wrong. I am a newbie to Java so please bear with me.
My code:
public class Hamburger {
private String name;
private double price;
private String breadRoll;
private String meat;
private String addition1Name;
private double addition1Price;
private String addition2Name;
private double addition2Price;
private String addition3Name;
private double addition3Price;
private String addition4Name;
private double addition4Price;
public Hamburger(double price, String meat) {
this.name = "Basic Hamburger";
this.price = price;
this.breadRoll = "White Bread";
this.meat = meat;
}
public void checkingAdditionCount(){
Scanner scanner = new Scanner(System.in);
System.out.println("Do you want to add more items?");
String answer = scanner.nextLine().toLowerCase();
boolean isCont = true;
while (isCont && scanner.hasNextLine()){
if (answer.equals("y")){
additions();
} else if (answer.equals("n")){
addAllItemsAndBill();
isCont = false;
scanner.close();
} else {
System.out.println("Please enter valid choice");
additions();
}
}
public void addAllItemsAndBill() {
System.out.println("Your total bill amount is " + this.price);
}
public void additions(){
Scanner scanner = new Scanner(System.in);
for (int count = 1; count < 5; count++){
System.out.println("Enter the addition name: ");
String additionName = scanner.nextLine();
System.out.println("Enter the addition price: ");
if (scanner.hasNextDouble()){
double additionPrice = scanner.nextDouble();
this.price += additionPrice;
}
scanner.nextLine();
checkingAdditionCount();
}
scanner.close();
this.addition1Name = name;
this.addition1Price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBreadRoll() {
return breadRoll;
}
public void setBreadRoll(String breadRoll) {
this.breadRoll = breadRoll;
}
public String getMeat() {
return meat;
}
public void setMeat(String meat) {
this.meat = meat;
}
}

Try code, like:
while(true) {
if(scanner.nextLine().equals("y")) break;
}
It will be looping until user input not equal 'y' :)

Related

Error cannot find symbol, method getcustomerdiscount() [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
Having an issue on line 192 in netbeans
cannot seem to figure out were the issue is
Line 192: System.out.println("Percent off: "+customer.getcustomerDiscount());
Error:
cannot find symbol
symbol: method getcustomerDiscount()
location: variable customer of type Customer
(PS yes i know it's in 1 java file, it's supposed to be)
package Driver2;
import java.util.Scanner;
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Person{
private String name;
private String address;
private String number;
private int customerPurchase;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
private int customerPurchase = 0;
private int customerDiscount;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
//#Override
//public int getcustomerPurchase()
//{
// return this.customerPurchase;
//}
public int getcustomerDiscount()
{
return this.customerDiscount;
}
//Mutators
/*
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver3
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
Additional
I am a little confused, i called the driver 1 and even made an object and couldent get it to work also another question popped up when i tested the if else statement another way
Question Should i leave the if else statement inside the setter? or put into the getter? i think i have an issue were i am not retrieving a string because it is all set as a INT
You are trying to call getcustomerDiscount on a Customer object. The method is not defined on this class but on Driver1.
Also: You should try to use Java naming conventions, in this case getcustomerDiscount and setcustomerDiscount should be renamed to getCustomerDiscount and setCustomerDiscount respectively.

How do I get user input from separate classes

My goal is to get an amount for an item and a description of that item. I want to get 10 inputs and their values. I don't know how to store their info without asking for one then the other. I want to be able to ask for the user to input the item then price and then store each of those values.
I was trying to create an array of objects to enter and then was suggested to use arraylists which I kind of understand but don't know how to implement in this case.
import java.util.ArrayList;
public class Invoice {
private ArrayList<Item> listOfItems;
public Invoice() {
listOfItems = new ArrayList<Item>();
}
public void addItem(Item item) {
listOfItems.add(item);
}
public double calculateNetItemCost() {
double netCost = 0;
for(Item currentItem : listOfItems) {
netCost += currentItem.getCost();
}
return netCost;
}
public double calculateTax(double taxRateAsADecimal) {
return calculateNetItemCost() * taxRateAsADecimal;
}
public double calculateGST() {
double GST = calculateNetItemCost() * 0.05;
return GST;
}
public double calculatePST() {
double PST = calculateNetItemCost() * 0.07;
return PST;
}
public double calculateTotalCost() {
double total = calculateGST() + calculatePST() + calculateNetItemCost();
return total;
}
}
public class Item {
private double amount;
private String description;
public Item(String description, double amount) {
this.amount = amount;
this.description = description;
}
public String toString() {
return description + ", $" + String.format("%.2f", amount);
}
public double getCost() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
import java.util.Scanner;
import java.util.ArrayList;
public class CustomerBuild {
public static void main(String[] args) {
ArrayList<String> description = new ArrayList<String>();
ArrayList<Double> amount = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
String userInput;
Item testItem = new Item("Apples", 4.00);
System.out.println(testItem);
Invoice testInvoice = new Invoice();
testInvoice.addItem(testItem);
double subTotal = testInvoice.calculateNetItemCost();
System.out.println(subTotal);
double GST = testInvoice.calculateGST();
System.out.println("GST: " + GST);
double PST = testInvoice.calculatePST();
System.out.println("PST: " + PST);
System.out.println("Total cost: " + testInvoice.calculateTotalCost());
}
}
This code snippet is what are you looking for. Asking the user for input then initializing the object using the values
Scanner input = new Scanner(System.in);
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
Item testItem = new Item(description, price);
For Looping:
for(int i =1;i<10;i++) {
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
testInvoice.addItem(new Item(description, price));
}

How to make an user-defined input in Class Stock

I'm having trouble doing a user-defined method in my program here, would it be nice if anyone can help me
package Ex_9_2;
public class TestStock {
public static String price;
//main
public static void main(String[] args) {
Stock stock = new Stock("ORCL", "Oracle Corporation");
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
System.out.println(stock);
// Display stock info
System.out.println("Previous Closing Price: " + stock.getPreviousClosingPrice());
System.out.println("Current Price: " + stock.getCurrentPrice());
System.out.println("Price Change: " + stock.changePercent());
}
}
Here's my other class
package Ex_9_2;
public class Stock {
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;
public Stock() {
}
public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}
public String getSymbol() {
return this.symbol;
}
public String getName() {
return this.name;
}
public double getPreviousClosingPrice() {
return previousClosingPrice;
}
public double getCurrentPrice() {
return currentPrice;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setName(String name) {
this.name = name;
}
public void setPreviousClosingPrice(double price) {
this.previousClosingPrice = price;
}
public void setCurrentPrice(double price) {
this.currentPrice = price;
}
public double changePercent() {
return (currentPrice - previousClosingPrice) / previousClosingPrice;
}
#Override
public java.lang.String toString(){
return "\nYour Company's name is " + this.name
+ "\nYour Company's Symbol is " + this.symbol;
}
I can't seem to make a user-input in my main for this problem:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
and this:
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
please help,
You can use java.util.Scanner class to take inputs from the user.
Declare a Scanner variable in your main function:
Scanner scan = new Scanner(System.in);
Then use scan.nexDouble() for taking input from the user. For example:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(scan.nextDouble());

Java: How would I declare an undefined number of object with user inputted data?

for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!
import java.util.Scanner;
public class Item
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
private String name;
private double price;
public static final double TOLERANCE = 0.0000001;
public Item(String name,double price)
{
this.name = name;
this.price = price;
}
public Item()
{
this("",0.0);
}
public Item(Item other)
{
this.name = other.name;
this.price = other.price;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public void setName(String name)
{
this.name = name;
}
public void setPrice(double price)
{
this.price = price;
}
public void input(String n, double item)
{
}
public void show()
{
// Code to be written by student
}
public String toString()
{
return "Item: " + name + " Price: " + price;
}
public boolean equals(Object other)
{
if(other == null)
return false;
else if(getClass() != other.getClass())
return false;
else
{
Item otherItem = (Item)other;
return(name.equals(otherItem.name)
&& equivalent(price, otherItem.price));
}
}
private static boolean equivalent(double a, double b)
{
return ( Math.abs(a - b) <= TOLERANCE );
}
}
As I understood you want just initialize an array of obects.
Firstly you need initialize an array:
int n = scanner.nextInt(); // you may get n in other way
Item[] items = new items[n];
Then you can fill it with new instances of Item:
for(int i = 0; i < n; i++){
items[i] = new Item(); //constructor args may be here
}
To add undefined number of object best choice is List in java. By using your example i add some code in main() method as below :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Item> items = new ArrayList<>();
while (true) {
System.out.println("--------------------------------");
System.out.print("Enter item name :: ");
String name = input.next();
System.out.print("Enter item price :: ");
while (!input.hasNextDouble()) {
System.err.println("Invalid Price (Double) eg. 300");
System.out.print("Enter item price :: ");
input.next();
}
double price = input.nextDouble();
Item item = new Item(name, price); //creating object by passing value in constructor
items.add(item); //adding object in list
System.out.println("Do you want to add more items ? 'Y'=>Yes or 'N'=>No ");
String ans = input.next();
if ("N".equalsIgnoreCase(ans)) {
break;
}
}
//To retrive item object list
for (Item i : items) {
System.out.println(i);
}
}

Updating Object in ArrayList

I've written this code and everything seems to be correct but unfortunately its not giving the correct units sold. im trying to find out if the salesperson ID exists and update that record. Sometimes it prints the right information and sometimes it does not.
import java.util.*;
public class salesPerson {
//salesPerson fields
private int salespersonID;
private String salespersonName;
private String productType;
private int unitsSold = 0;
private double unitPrice;
//Constructor method
public salesPerson(int salespersonID, String salespersonName, String productType, int unitsSold, double unitPrice)
{
this.salespersonID = salespersonID;
this.salespersonName = salespersonName;
this.productType = productType;
this.unitsSold = unitsSold;
this.unitPrice = unitPrice;
}
//Accessor for salesPerson
public int getSalesPersonID(){
return salespersonID;
}
public String getSalesPersonName(){
return salespersonName;
}
public String getProductType(){
return productType;
}
public int getUnitsSold(){
return unitsSold;
}
public double getUnitPrice(){
return unitPrice;
}
public double getTotalSold(){
return unitsSold * unitPrice;
}
//Mutoators for salesPerson
public void setSalesPersonID(int salespersonID){
this.salespersonID = salespersonID;
}
public void setSalesPersonName(String salespersonName) {
this.salespersonName = salespersonName;
}
public void setProductType(String productType){
this.productType = productType;
}
public void setUnitsSold(int unitsSold){
this.unitsSold = this.unitsSold + unitsSold;
}
public void setUnitProce(double unitPrice){
this.unitPrice = unitPrice;
}
public static void main(String[] args)
{
ArrayList<salesPerson> salesPeople = new ArrayList<salesPerson>();
Scanner userInput = new Scanner(System.in);
boolean newRecord = true;
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
do{
System.out.println("Please enter the Salesperson Inoformation.");
System.out.print("Salesperson ID: ");
salespersonID = userInput.nextInt();
System.out.print("Salesperson Name: ");
salespersonName = userInput.next();
System.out.print("Product Type: ");
productType = userInput.next();
System.out.print("Units Sold: ");
unitsSold = userInput.nextInt();
System.out.print("Unit Price: ");
unitPrice = userInput.nextDouble();
if(salesPeople.size() == 0)
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
else
{
for(int i=0; i < salesPeople.size(); i++) {
if(salesPeople.get(i).getSalesPersonID() == salespersonID)
{
salesPeople.get(i).setUnitsSold(unitsSold);
}
else
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
//System.out.println(salesPeople.get(i).getSalesPersonName());
}
}
System.out.print("Would you like to enter more data?(y/n)");
String askNew = userInput.next();
newRecord = (askNew.toLowerCase().equals("y")) ? true : false;
}while(newRecord == true);
for(int i=0; i < salesPeople.size(); i++) {
System.out.println(salesPeople.get(i).getSalesPersonName() + ": "+salesPeople.get(i).getUnitsSold());
}
}
}
This method is probably wrong:
public void setUnitsSold(int unitsSold){
this.unitsSold = this.unitsSold + unitsSold;
}
Replace it by:
public void setUnitsSold(int unitsSold){
this.unitsSold = unitsSold;
}
You also have a problem on your main() method: The for creates a new SalesPerson instance for each element that has a different id from the one you've received on the input.
It's not related with your problem, but you should always (and I mean ALWAYS) start the name of Java classes with capital letters.

Categories

Resources