Why are my codes error today and fine yesterday? - java

import java.util.Scanner;
public class CarTest {
/**
* #param args
*/
public static void main(String[] args) {
//create a Scanner object
Scanner input = new Scanner(System.in);
/**
*Creates a car! object from the Car class
*with the passing of these arguments
*year, make, model, price
*/
Car car1 = new Car("2008", "Nissan", "Pathfinder", "10,000");
//display toString using car1 object
System.out.println(car1.toString());
//user input for year
System.out.println("Please list your automobile for sale: " +
"\nPlease enter the year? ");
//String newYear variable is created for CarTest class
String newYear = input.nexLine();
//set year in car class for Car1 object to String newYear
car1.setYear(newYear);
//user input for make
System.out.println("Please enter the make? ");
//String newMake variable is created for CarTest class
String newMake = input.nextLine();
//set make in car class for Car1 object to String newMake
car1.setMake(newMake);
//user input for model
System.out.println("Please Enter the model?");
//String newModel variable is created for CarTest class
String newModel = input.nextLine();
//set model in car class for Car1 object to String newModel
car1.setModel(newModel);
//user input for price
System.out.println("How much would you sell your car for?");
//String newPrice variable is created for CarTest class
String newPrice = input.nextLine();
//set price in car class for Car1 object to String newPrice
car1.setPrice(newPrice);
//displays the new info to the screen
System.out.println(car1.toString());
}
}
from
public class Car {
//class variables are created
private String year;
private String make;
private String model;
private String price;
//default constructor
public Car() {
}
//constructor with arguments
public Car(String year, String make, String model, String price) {
this.year = year;
this.model = model;
this.make = make;
this.price = price;
}
//get make of the vehicle
public String getMake() {
return make;
}
//set make for vehicle
public void setMake(String make) {
this.make = make;
}
//get model of the vehicle
public String getModel(){
return model;
}
//set model for vehicle
public void setModel(String model) {
this.model = model;
}
//get price of the vehicle
public String getPrice() {
return price;
}
//set price for vehicle
public void setPrice(String price) {
this.price = price;
}
//get year of the vehicle
public String getYear() {
return year;
}
//set year for vehicle
public void setYear(String year) {
this.year = year;
}
public String toString() {
return "For Sale By Owner: " + year + " " + make + " " + model +
"\nSelling Price: $" + price + "\n ";
}
}
It worked fine when i handed it last week for an assignment, but today, when i came to my computer for a new homework, I found red x's on my car.java, and carTest.java.
My eclipse is saying that : from carTest.java is full of errors and:
error: main method not found in class homework.cartest. please define the main method
public static void main(String[] args)
error is in the way I defined CAR1:
Car car1 = new Car("2008", "Nissan", "Pathfinder", "10,000");
and the ways i am getting the inputs
String newYear = input.nexLine();
String newMake = input.nextLine();
String newModel = input.nextLine();
String newPrice = input.nextLine();
with the input.nextLine(); being underlined as an error in the code in eclipse.
also in the Car.java. the method String toSTring() causes an error stating "change toString() type to String type.
it worked fine when I handed it and got a good grade for it, but today I noticed my codes to be errors, when all was okay yesterday?

Is the file listed under package/project Homework?
If not, reading your error-message correctly, you're trying to run something that doesn't exist.
At the same time, as said above, you could be experiencing filepath issues. Creating a new project and copy-pasting your code (refactored copy) is usually the quickest solution.

Clean and build the project. May be an anomaly with your Java build path

Copied your project and runned it. Only thing that is wrong with it is:
String newYear = input.nexLine();
should be:
String newYear = input.nextLine();
For the rest, it works fine.
And in the toString method you should add an #override annotation
#Override
public String toString() {
return "For Sale By Owner: " + year + " " + make + " " + model
+ "\nSelling Price: $" + price + "\n ";
}
Also make sure your project is called CarTest and Source packages package cartest

Related

How can i access the variable from different class method

This is the main file, im trying to print the result of the Age, Name, Birthdate, etc.
LabExercise1
package labexercise1;
/**
*
* #author user
*/
public class LabExercise1{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NewClass newClass = new NewClass();
NewClass.getFirstName();
NewClass.getLastName();
NewClass.getAge();
NewClass.getBirthDate();
NewClass.getGWA();
// TODO code application logic here
System.out.println("My name is " + FirstName + "." + " I am " + Age + " years old and the day that i was born is on " + BirthDate + ". My general weighted average this semester is " + GWA + ".");
}
NewClass
package labexercise1;
import java.util.Scanner;
/**
*
* #author user
*/
public class NewClass {
public static void getFirstName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter First Name: ");
String FirstName = myObj.nextLine(); // Read user input
}
public static void getLastName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Last Name: ");
String LastName = myObj.nextLine(); // Read user input
}
public static void getAge(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age: ");
int Age = myObj.nextInt();
}
public static void getBirthDate(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your BirthDate: ");
String BirthDate = myObj.nextLine();
}
public static void getGWA(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your GWA: ");
float GWA = myObj.nextFloat();
}
}
A lot of this is basic Java 101, concepts and ideas which you should be building around "what is an object".
I would, highly, recommend taking the time to go through things like...
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Understanding Class Members
For example...
import java.text.ParseException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Birthdate: ");
String dateOfBirth = scanner.nextLine();
System.out.print("Enter GWA: ");
int gwa = scanner.nextInt();
scanner.nextLine();
Person person = new Person(firstName, lastName, age, dateOfBirth, gwa);
System.out.println("First name = " + person.getFirstName());
System.out.println("Last name = " + person.getLastName());
System.out.println("Age = " + person.getAge());
System.out.println("Date of birth = " + person.getDateOfBirth());
System.out.println("GWA = " + person.getGwa());
}
public class Person {
private String firstName;
private String lastName;
private int age;
private String dateOfBirth;
private int gwa;
public Person(String firstName, String lastName, int age, String dateOfBirth, int gwa) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.gwa = gwa;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public int getGwa() {
return gwa;
}
}
}
Please keep in mind, Stack overflow is NOT a tutorial site/forum and you will, ultimately, be expected to make the effort to learn these basic concepts.

Having trouble with constructors and user-input

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.

Instantiate error when I change class to abstract

I'm working on my intro to programming assignment. Previously I created a program that models an employee using classes for Address Name and Date. This week the assignment is adding subclasses for Hourly and Salaried employees. To start with I tried making my employee class abstract, but when I do that, I get an error in my ArrayList "Cannot instantiate the type Employee (I put in a comment that shows where this error is)" I have posted my code below-- If anyone could give me any suggestions I would really appreciate it I've been struggling with what to do for hours.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public abstract class Employee
{
private int id;
private Name name;
private Address address;
private Date date;
Employee (int id, Name name, Address address, Date date)
{
setId(id);
setName(name);
setAddress(address);
setDate(date);
}
//Setter
public void setId(int id)
{
this.id = id;
}
public void setName(Name name)
{
this.name = name;
}
public void setAddress(Address address)
{
this.address = address;
}
public void setDate(Date date)
{
this.date = date;
}
//Getter
public int getId()
{
return id;
}
public Name getName()
{
return name;
}
public Address getAddress()
{
return address;
}
public Date getDate()
{
return date;
}
public String toString()
{
return "ID: " +getId()+ "Name: " +getName()+ "Address: " +getAddress()+ "Hire Date: "+ getDate();
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Ask user for number of employees; create array of appropriate size
System.out.println("Enter the number of employees: ");
int numEmployees = input.nextInt();
List<Employee> employees = new ArrayList<>();
// Read information on individual employees.
for (int i = 0; i < numEmployees; i++)
{
System.out.println("Enter the employee ID number: " );
int id = input.nextInt();
input.nextLine(); //without this the scanner skips
System.out.println("Enter the first name of the employee: " );
String firstName = input.nextLine();
System.out.println("Enter the last name of the employee: " );
String lastName = input.nextLine();
System.out.println("Enter the street address of the employee: " );
String street = input.nextLine();
System.out.println("Enter the city where the employee resides: " );
String city = input.nextLine();
System.out.println("Enter the state where the employee resides (two letter abbreviation): " );
String state = input.nextLine();
System.out.println("Enter the zip code of the employee: " );
String zip = input.nextLine();
System.out.println("Enter the month the employee was hired (1-12): " );
int month = input.nextInt();
System.out.println("Enter the day the employee was hired (1-31): " );
int day = input.nextInt();
System.out.println("Enter the year the employee was hired (1900-2020): " );
int year = input.nextInt();
input.nextLine(); //without this the scanner skips to last name
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
//this is where I get the error
Employee employee = new Employee(id, name, address, date);
employees.add(employee);
}
/**
* Print out information on all the employees
* Use Foreach loop to iterate through ArrayList
**/
for(Employee employee : employees)
{
System.out.print("ID:" + employee.getId() + " ");
System.out.print("Name:" + employee.getName().getFirstName() + " ");
System.out.println(employee.getName().getLastName());
System.out.print("Address:" + employee.getAddress().getStreet() + " ");
System.out.print(employee.getAddress().getCity() + " ");
System.out.print(employee.getAddress().getState() + " ");
System.out.println(employee.getAddress().getZip());
System.out.print("Hire Date: " + employee.getDate().getMonth() + "/");
System.out.print(employee.getDate().getDay() + "/");
System.out.println(employee.getDate().getYear());
System.out.println();
}
input.close();
}
}
You cannot instantiate abstract classes in Java. You can, however, instantiate a quick non-abstract subclass from them. In this subclass you'd of course need to implement all methods that are abstract as well
abstract class Foo {
...
}
public static void main(String args[]) {
Foo foo = new Foo(); //Can't do
Foo foo = new Foo() {}; // this will work, as long as Foo has a null constructor; if Foo has abstract methods, make sure to define them concretely within the { ... } block
}
Usually abstract classes are used to provide the basic data/methods to subclasses.
You cannot instantiate an object of abstract class.*
It's just a level of program abstraction and a good practice to create a hierarchical class structure.
*But you may use a reference to abstract class for creating an object of a concrete type.
AbstractClass obj = new ConcreteClass(); // if ConcreteClass extends AbstractClass
Making a class abstract usually means that it will be used as a parent class for subclasses that need to implement the same methods. Abstract classes cannot be instantiated. Once you have created your required subclasses, HourlyEmployee and SalariedEmployee, you'll be able to define a new object like this:
Employee employee = new HourlyEmployee();
or
Employee employee = new SalariedEmployee();
Here's a great explanation regarding abstract classes: https://stackoverflow.com/a/1320887/6062407

arraylist with method

As my last question obviously was a little bit unclear (I applogise for that), I'm making a new try, and this time I will really try to be clear.
Here is the code I have written so far
Main class:
import java.util.*;
public class Head {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String fname, lname;
int choice;
ArrayList<People>list = new ArrayList<>();
People p1 = new People("Mia", "Wallace", "1111");
People p2 = new People("Marcellus", "Wallace", "2222");
list.add(p1);
list.add(p2);
System.out.println("Welcome");
System.out.println("1) Add person \n2) Last name \n3) Print list");
choice = scan.nextInt();
switch(choice){
case 1:
People.walk(); //calling the method
break;
case 2:
People.run();
break;
case 3:
People.crawl();
break;
}
}
}
People class:
import java.util.*;
public class People {
static Scanner scan = new Scanner(System.in);
private static String fname;
private static String lname;
private static String dob;
public People(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public static void walk(){
System.out.println("Enter first name: ");
fname = scan.next();
System.out.println("Enter last name: ");
lname = scan.next();
System.out.println("Enter dob: ");
dob = scan.next();
list.add(new People(fname, lname, dob)); **//list cannot be resolved**
}
public static void run(){
System.out.println("Remove people");
}
public static void crawl(){
int peoplenumber = 0;
System.out.println("\nNumber of peoples: " + list.size()); **//list cannot be resolved**
for(People p : list){ **//list cannot be resolved**
peoplenumber += 1;
System.out.println("#" + peoplenumber + "\n" + p.toString());
}
}
public String toString(){
return "First name: " + this.fname + "\nLast name: " + this.lname + "\nDateOfBirth: " + this.dob;
}
}
I do understand why I get the error, but I don't know how to get around it. Any help?
Am I right when I try to move code from the main-class to the costructors?
If you guys have any comments or ideas how I should solve this, or move on with java, I will gladly here them.
Thank you very much for your time and your help :)
The arraylist should be in the main class. If it were in the person class, it would be created once for every person object you create. To access a method for that person, you want to call the name of the OBJECT (not the type), the .method(parameters).
If you wanted to call run on p1 (not really sure what you want to call it on), you would use:
p1.run();
That would perform the code in the run method where it is defined.

Car Program using Getters and Setters Issues

For this Program the instance variables make and model need to be a string, price needs to be a double which I already have, but not sure what to do with year that needs to be of type int and greater then 1900. I then need to make a constructor with argument which I have done as well but the toString needs to return the string representation of a Car object with the setters and getters methods. So I am having an issue trying to come up with something for the setters and if I am doing this section right.
public class Car {
private String make;
private String model;
private double price;
private int year;
public Car(String make, String model, double price, int year) {
this.make = make;
this.model = model;
this.price = price;
this.year = year;
}
private String getMake() {
return make;
}
private void setMake(String make) {
this.make = make;
}
private String getModel() {
return model;
}
private void setModel(String model) {
this.model = model;
}
private double getPrice() {
return price;
}
private void setPrice(double price) {
this.price = price;
}
private int getYear() {
return year;
}
private void setYear(int year) {
this.year = year;
}
public String toString() {
return "Make of Car: " + getMake() + "\n Model of Car: " + getModel()
+ "\n Price of Car: " + getPrice() + "\n Year of Car: " + getYear();
}
}
This section is the CarTest driver and I am not sure if I did this properly. I have to have a Main method that Instantiates a Car object car1 by invoking the argument constructor and display to the console the string representation of the object car1 using the method toString. Also asking the user to enter values for each instance variable and use the setter type methods to assign the entered values to the corresponding instance variables of the object car1 then I need to display the string representation of the object car1 by invoking the toString method. Am I doing this part right?
public class CarTest {
static Car car1;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Make?");
String make = scan.nextLine();
System.out.print("Model?");
String model = scan.nextLine();
System.out.print("Price?");
double price = scan.nextDouble();
System.out.print("Year?");
int year = scan.nextInt();
car1 = new Car(make,model,price,year);
System.out.print(car1.toString());
}
}
You can either do the checking when taking the user input, or the constructor (or both)
int year = 0;
while (year < 1900) {
System.out.println("Year? ");
year = scanner.nextInt();
}
Everything looks good to me. Maybe you don't need to have the getters if you have the toString method, which returns all the attributes of the car. Juste have the variables and the to string in the return and remove the getters
Good work!

Categories