Testing (if..Else if...Else) statement (not working) - java

Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work
//package Driver2;
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//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;
}
public void setcustomerDiscount(int r)
{
r = this.customerPurchase;
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 Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;
//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;
}
public int getcustomerDiscount()
{
return customerDiscount;
}
//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;
//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
/*
public int getcustomerDiscount()
{
return this.customerDiscount;
}
/*
#Override
public int getcustomerPurchase()
{
return this.customerPurchase;
}
//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("");
}
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{
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());
}
}

The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.
1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.
2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.
3) Another thing is your order of the if/else if conditions should be in descending order.
Once you fix them, you can get your output as expected.
Below I have made those changes:
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//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;
}
public void setcustomerDiscount(int r)
{
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//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;
}
public String getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
public void setcustomerDiscount(int r)
{
String customerDiscount = "";
if (r >= 2000)
{
customerDiscount="10%";
System.out.print("10%");
}
else if (r >= 1500)
{
customerDiscount="7%";
System.out.print("7%");
}
else if (r >= 1000)
{
customerDiscount="6%";
System.out.print("6%");
}
else if (r > 500)
{
customerDiscount="5%";
System.out.print("5%");
}
else
{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
public class TestMain
{
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();
scanner.close();
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());
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
Hope it helps...

I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:
if r >= 2000 print 10%
else if r >= 1500 print 7%
else if r >= 1000 print 6%
else if r >= 500 print 5%
else print nothing
I hope that helps you

Related

Taking user input for the objects

Question : Create a two objects of class Employee and check both are same or diffrent
Below code gives an error : Exception in thread "main" java.util.InputMismatchException
Only object e1 accepts values
class Employee {
String name;
int age;
char gender;
public Employee() {
super();
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
public class Source {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee e1 = new Employee();
//e1.name = sc.nextLine();
//e1.age = sc.nextInt();
//e1.gender = sc.next().charAt(0);
System.out.println(e1.name+" "+e1.age+" "+e1.gender);
Employee e2 = new Employee();
//e2.name = sc.nextLine();
//e2.age = sc.nextInt();
//e2.gender = sc.next().charAt(0);
System.out.println(e2.name+" "+e2.age+" "+e2.gender);
boolean isSame = e1.equals(e2);
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
}
}
How to take user input or input from keyboard for objects e1 and e2?
I have made some changes to your Employee and Source classes, take a look.
public class Source {
Scanner sc = null;
public static void main(String[] args) {
Source source = new Source();
Employee e1 = source.getEmployee();
Employee e2 = source.getEmployee();
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
source.closeScanner();
}
public Source() {
sc = new Scanner(System.in);
}
public void closeScanner() {
sc.close();
}
public Employee getEmployee() {
Employee e = new Employee();
System.out.print("Enter Name: ");
e.name = sc.next();
System.out.print("Enter Age: ");
e.age = sc.nextInt();
System.out.print("Enter Gender: ");
e.gender = sc.next().charAt(0);
System.out.println(e.getName() + " " + e.getAge() + " " + e.getGender());
return e;
}
}
public class Employee {
String name;
int age;
char gender;
public Employee() {
super();
int age = -1;
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + gender;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (gender != other.gender)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Please note that I've added the following two methods
public int hashCode()
and
public boolean equals(Object obj)
to make it possible to compare the two instances of the employee object

System out print incorrect. Possible Accessor or Mutator mistake [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Having an issue with this section of code first stated below
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
It is printing "5%Percent off: 5%"
But when I remove the front 5% the code will print Percent off: null
I am looking to find a way for it to instead print "Percent off: 5%"
Possible problem area is in the setter, and wondering if i should move the if else statement to have the getter grab it instead.
Working with the code and moving pieces around trying to solve the puzzle
code in its current state works perfectly other then that
Full Code
package driver2;
import java.util.Scanner;
import java.text.DecimalFormat;
class Person{
private String name;
private String address;
private String number;
private double customerPurchase = 0;
//////// 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 double 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;
}
public void setcustomerDiscount(int r)
{}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//////// 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;
}
public String getcustomerDiscount(){
return customerDiscount;
}
//////// Mutators /////////
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
#Override
public void setcustomerDiscount(int r){
String customerDiscount = "";
if (r >= 2000){
customerDiscount="10%";
System.out.print("10%");
}else if (r >= 1500){
customerDiscount="7%";
System.out.print("7%");
}else if (r >= 1000){
customerDiscount="6%";
System.out.print("6%");
}else if (r > 500){
customerDiscount="5%";
System.out.print("5%");
}else{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Driver2{
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();
scanner.close();
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());
DecimalFormat ft = new DecimalFormat("####");
ft = new DecimalFormat("$0.00");
System.out.println("Amount Purchased: "+ft.format(customer.getcustomerPurchase()));
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
The problem is this:
customerDiscount="5%";
System.out.print("5%"); // remove this
That prints the "5%" before you print the rest:
System.out.println("Percent off: "+ customer.getcustomerDiscount());
If you remove the first print (with "remove this" comment above), you'll print what you intended.

Java Program Unable to receive the input and program terminated prematurely

I'm not sure y this coding is not receiving the input for the adjust variable and gets terminated before it runs completely
public class Question {
int id;
String name;
String type;
double amt;
public Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
public static void main(String[] args)
{ }
}
import java.util.*;
public class Answer {
public static void gettype(Question[] q,String adjust)
{
for(int i=0;i<2;i++)
{
if(q[i].getType()==adjust)
{
System.out.println(q[i].getId());
}
}}
public static void main(String[] args) {
int id;
String name,type,adjust;
double amt;
Scanner s=new Scanner(System.in);
Answer a=new Answer();
System.out.println("enter 2 car inputs");
Question[] q=new Question[2];
for(int i=0;i<2;i++)
{
id=s.nextInt();
s.nextLine();
name=s.nextLine();
type=s.nextLine();
amt=s.nextDouble();
q[i]= new Question(id,name,type,amt);
}
adjust=s.nextLine();
a.gettype(q,adjust);
}
}
While running the code i am able to get the inputs for the car object array.But after that i am not able to get the values for the variable adjust.
So please need help with this one.
I have tried simply to print the objects at the constructor side.
But not able to receive the 9th input which will be assigned to the var adjust
I think this is better. You should understand why mine works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Question {
private int id;
private String name;
private String type;
private double amt;
Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
int getId() {
return id;
}
String getName() {
return name;
}
String getType() {
return type;
}
double getAmt() {
return amt;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Question{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", amt=").append(amt);
sb.append('}');
return sb.toString();
}
}
class Answer {
public static final int NUM_QUESTIONS = 2;
public static void main(String[] args) {
int numQuestions = (args.length > 0) ? Integer.valueOf(args[0]) : NUM_QUESTIONS;
List<Question> questions = new ArrayList<>();
Scanner s = new Scanner(System.in);
for (int i = 0; i < numQuestions; ++i) {
System.out.println(String.format("Question %d", i));
System.out.print("id: ");
int id = s.nextInt();
System.out.print("name: ");
String name = s.next();
System.out.print("type: ");
String type = s.next();
System.out.print("amt: ");
double amt = s.nextDouble();
questions.add(new Question(id, name, type, amt));
}
System.out.println(questions);
}
}

JAVA How to compare integer using compareTo in this exercise

I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}

How to sort ArrayList Java

I have this arrayList that i need to first sort from greatest to least by both item price and then after i need to sort it by the amount of items sold. Whats the easiest way to accomplish this? thanks!
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 += 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;
boolean showReport = true;
do
{
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
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);
break;
}
else
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
break;
}
//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);
Write a custom comparator:
public SalesPersonComparator implements Comparator<salesPerson> {
public int compare(final salesPerson p1, final salesPerson p2) {
// get the comparison of the unit prices (in descending order, so compare p2 to p1)
int comp = new Double(p2.getUnitPrice()).compareTo(new Double(p1.getUnitPrice()));
// if the same
if(comp == 0) {
// compare the units sold (in descending order, so compare p2 to p1)
comp = new Integer(p2.getUnitsSold()).compareTo(new Integer(p1.getUnitsSold()));
}
return comp;
}
}
Edit (thanks to #Levenal):
Then use Collections.sort() to sort your list.

Categories