I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.
Related
I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.
I am quite new to java and am having a problem trying to store user input to an array to later be able to call the list, however I am getting an error when trying to do so. The error comes on the newvoter.add(); line. Sorry if I'm being ignorant in any way, I feel like I'm being stupid!
public class admin {
public static Scanner sc = new Scanner (System.in);
public static List<voter> Voters = new ArrayList<voter>();
public static int promptUserInput() {
System.out.print("\n\tEnter: ");
int option = sc.nextInt();
return option;
}
public static int getOption() {
int option = promptUserInput();
switch(option){
case 1:
addVoter();
break;
case 2:
//deleteVoter();
break;
case 3:
Questions openQuestions = new Questions();
openQuestions.addQuestion();
break;
case 4:
break;
case 5:
System.out.println("Programme Ended");
System.exit(0);
default:
break;
}
return option;
}
public static void main(String[] args) {
printMenu();
}
public static void printMenu(){
System.out.println("\nAdmin Options Menu\n"
+ "\t\nPlease enter an option:\t\n"
+ "\n\t\t1: Create Voter\t\n"
+ "\t\t2:Delete Voter\t\n"
+ "\t\t3:Add Questions\t\n"
+ "\t\t4: View Questions List\t\n"
+ "\t\t5: Delete Question\t\n");
getOption();
}
private static void addVoter(){
voterAdd newvoter = new voterAdd(); // Creates a new voter
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Surname Name: ");
String surname = sc.next();
System.out.println("Enter Voter ID: ");
int voterID = sc.nextInt();
System.out.println("Enter City: ");
String city = sc.next();
newvoter.setVoter(firstName, surname, voterID, city);//calls the 'setVoter' method inherited from 'voter'
newvoter.add();//adds the 'newVoter' to the ArrayList 'voter'
System.out.println("\n New voter identification has been created and stored.\n");
listVoters();
}
Here is the class it calls from..
public class voterAdd {
private String firstName = "";
private String surname = "";
private int voterID = 0; //voterID of the voter
private String city = "";
public void setVoter(String firstName, String surname, int voterID, String city) {
this.firstName = firstName;
this.surname = surname;
this.voterID = voterID;
this.city = city;
}
public String getFirstName()
{
return firstName;
}
public String getsurname()
{
return surname;
}
public int getID()
{
return voterID;
}
public String getCity()
{
return city;
}
}
It's Voters.add(newvoter);, not newvoter.add(). Also, variable names should start with a lowercase letter or an underscore. Classes should start with uppercases.
Well one of your problems is that you are calling in your List the voter class, when maybe it should be the voteradd class like such:
List<voteradd> listName = new List<voteradd>();
Another thing, common java principles expect java classes to start with a capital letter(camel case), it's just good conventions and good practice. Hopefully this helped, best of luck :)
i was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constructor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constructor to create new objects with it? And how these new objects will be called?
import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){
this.name=name;
this.age= age;
System.out.println("this is "+name+", and he is "+age+" old.");
}
public static void AskUSer(){
int x=0;
do {System.out.print("what's the name of the person ?");
name= a.nextLine();
System.out.print("how old is he? ");
age= b.nextInt();
System.out.print("would u like to creat another person ");
String yes = c.nextLine();
if(!(yes.equals("yes"))){x++;}
} while(x==0);
}
public static void main (String[] args){
AskUSer();
System.out.print(age+ " "+ name);
}
}
You can construct the new object in AskUSer and return it as return value. So the code would look like:
public static YourObject AskUSer() {
...
}
aside from how you read from the user ,
it will be appropriate to make a class..
something like :
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
and before entering the loop
you could use an ArrayList to hold people
ArrayList<Person> people = new ArrayList<Person>();
and each time you read the inputs .. instantiate a Person object and add it to the ArrayList
something like :
Person pr=new Person(name,age);
people.add(pr);
I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}
The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}
Trying to use setVaraible() to make the String "Hometown" equal user input, so it can be called back later. Someone else previously helped me with something of this nature, but it was used in a loop, so I can't exactly see how it worked.
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
private static String Hometown;
It looked like this:
while (sc.hasNext()) {
input = sc.next();
System.out.println("");
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine, " + InputName
+ ", so, you are " + Age + " years old and " + Sex + "." );
System.out.println("");
sleep();
System.out.println("Do you need to change any information?\n");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
And, I just need it here (I know this code is wrong):
static public void Intro() {
int a = 0;
setVariable(3, Hometown);
String[] questions = {"What do you want to name your hometown?"};
System.out.println(questions);
input = sc.next();
}
Here is the setVariable() method:
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
case 3:
Hometown = Field;
return;
}
}
Basically, you can call setVariable by passing it two values, the first is a int value which represents field to be set and the second is the value to apply, for example
setVariable(0, "This is the input name");
Would set the InputName variable to "This is the input name"
Using 1 would allow you to change the Age variable, 2 the Sex variable and 3 the Hometown variable, so basically, what you need to try is something like...
setVariable(3, "New home town value");
For example...
Currently your code looks something like...
static public void Intro() {
int a = 0;
setVariable(3, Hometown);
String[] questions = {"What do you want to name your hometown?"};
System.out.println(questions);
input = sc.next();
}
Which basically assigns the current value of Hometown to itself...which is probably null, then you try and read a value from the Scanner
Try it the other way round, for example...
static public void Intro() {
System.out.println("What do you want to name your hometown?");
input = sc.nextLine();
setVariable(3, input);
}
Making sure you pass the input value to the method, so it can assign the value to the correct field...
Personally, I don't find this either useful or intuitive. Sure you could use an enum or even define static final variables that would make determine which field you want to change easier, but Java is an Object Oriented language, we might as well make use of it...
I would encourage you to define a Person object (for argument sake) with which you can set/get the individual properties of the object, for example...
public class Person {
private String inputName;
private String sex;
private String age;
private String hometown;
public void setName(String name) {
this.inputName = name;
}
public String getName() {
return inputName;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setAge(String age) {
this.age = age;
}
public String getAge() {
return age;
}
public void setHometown(String hometown) {
this.hometown = hometown;
}
public String getHometown() {
return hometown;
}
}
Then you would simply create a new instance of Person
Person person = new Person();
And fill it out...
person.setName("Ruphet");
person.setSex("Male");
person.setAge("18");
person.setHometown("Murembugie");
And when you need to show or "get" some value...
System.out.println("Hello " + person.getName() + " from " + person.getHometown());
ps-
You might like to take a read through Code Conventions for the Java Programming Language, it will make it easier for others to read your code (and for you to read others)...
Try something like this.
// This method should not be static, but your Hometown is.
public static void setHometown(String input) {
// This should not be a static variable, also it shouldn't be capitalized.
if (input == null) {
Hometown = "";
} else {
Hometown = input;
}
}