infile class. Constructor undefined - java

It keeps telling me that my constructor Pet is undefined. Any ideas?
I've tried defining Pet in my main method prior to the while loop, but it gives me the same issue.
import java.util.*;
import java.io.*;
public class ReadPets
{
public static void main (String[] args)
{
ArrayList <Pet> petList = new ArrayList <Pet>();
Scanner inFile = null;
String name;
Pet p;
try
{
inFile = new Scanner
(new FileInputStream ("pets.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("problem opening file.");
System.exit(0);
}
while (inFile.hasNextLine())
{
name = inFile.nextLine();
p = new Pet(name); // here is where my error is
petList.add(p);
}
inFile.close();
}
}
Here is my Pet class.
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
/**
This main is just a demonstration program.
*/
public static void main(String[] args)
{
Pet myDog = new Pet( );
myDog.set("Fido", 2, 5.5);
myDog.writeOutput( );
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput( );
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput( );
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput( );
}
public void writeOutput( )
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}
}

Your Pet class does not have a constructor that takes a String which is what you are trying with this line
p = new Pet(name)
Either make one or do something similar to the demonstration, which is make the new Pet instance and then call set("Name") on this instance
Like:
p = new Pet();
p.set(name);

I do not see any constructors in your Pet class which means that Java will provide a default (no argument) constructor for you.
This is why the following statement is OK:
Pet myDog = new Pet( );
The statement that you have a problem with uses a constructor with an argument, that you have not defined.
You will need either to create such constructor (Pet(String name) {...}) or change your logic to use default constructor and your set() method.
Be warned as soon as you define any constructor, Java will no longer create a default constructor for you, so you will need to do it yourself.

You required to write one parametrized constructor in our Pet class with one String.

Related

How to stop the program when pressing a certain button on the keyboard, for example s

I am new to programming and at the moment I am doing a task, the essence of which is the emulation of scanning a person by gender and age with a further pass to a zone defined for its parameters. I was told to supplement the program so that, for example, when you press the S button on the keyboard, the program ends.
Please tell me how can I implement this. I have 4 classes in my code:
main
public class Main {
public static void main(String[] args) {
PassportScan passportScan = new PassportScan();
Guard guard = new Guard();
while (true) {
Person person = passportScan.methodScan();
String result = guard.checkPerson(person);
System.out.println(result);
}
}
}
PassportScan
import java.util.Scanner;
public class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
Person
public class Person {
private String gender;
private Integer age;
public Person(String gender, Integer age) {
this.gender = gender;
this.age = age;
}
public String getGender() {
return gender;
}
public Integer getAge() {
return age;
}
}
Guard
public class Guard {
public String checkPerson(Person personToCheck) {
String gender = personToCheck.getGender();
int age = personToCheck.getAge();
if (age < 18 && gender.equals("M")) {
return "Zone 1";
}
if (age >= 18 && gender.equals("M")) {
return "Zone 2";
}
if (age < 18 && gender.equals("F")) {
return "Zone 3";
}
if (age >= 18 && gender.equals("F")) {
return "Zone 4";
}
return "";
}
}
Thanks in advance for the tip and your time!
Basically there will be two scenario for this.
1. Once Press S >>> You want to terminate the program
Simply its not available in normal console
but there is way to achieve refer this post for more info https://stackoverflow.com/a/1066647/8524713
2. Press S and then press Enter key >>
In this case its easy
check on each gender input if its S break the loop
try below code for reference
public static void main(String[] args) {
PassportScan passportScan = new PassportScan();
Guard guard = new Guard();
while (true) {
Person person = passportScan.methodScan();
//checking if person object is null if ts null means s is enter
// break from loop
if(person==null) {
break;
}
String result = guard.checkPerson(person);
System.out.println(result);
}
}
static class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
//check if string input is S or s
// then its returning null person object
if(gender.equalsIgnoreCase("s")) return null;
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
one more way is to directly terminate in PassportScan class once S is typed
class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
//check if string input is S or s terminating prog
if(gender.equalsIgnoreCase("s")) System.exit(0)
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
You probably have some Component in that you display something, for example a (class that extends) JFrame, lets call it c.
Now call:
c.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (Character.toLowerCase(e.getKeyChar()) == 's') System.exit(0);
}
#Override
public void keyReleased(KeyEvent e) {
}
});
It is not possible to catch a KeyEvent without a GUI (When you think about it, how should Java know that the key was pressed in your application? If it would catch any KeyEvent on the device, you could easily build spyware that catches passwords or sth.)

Exception thrown while calling scanner more than once. "Exception in thread main" java.util.NoSuchElementException: No line found"

I am pretty new at Java and am just learning so please be kind.
I am doing a coding Inheritance challenge and I'm trying to use user inputs to set up a car before driving.
When I call the 2 methods I am using to set the parameters with Scanner this first method testCar.drivingTest() works fine, however when testCar.carAgeType() is called, I get an exception.
Below are the requests and inputs as well as the exception.
Would you like to test a used car today? : y or n
y
great , do you have a driving licence :type: big, medium or small
big
Great you passed your 'big' exam. Lets check the MOT : type: pass or fail
pass
What type of car were you looking for :type: sports , town or 4X4
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at learning.java.Car.carAgeType(Car.java:30)
at learning.java.Main.main(Main.java:17)
Process finished with exit code 1
From what I can gather searching google most people use .hasNextLine() to check something but I don't know what to do or why this is coming back as false on testCar.carAgeType. both methods use basically the same code and when I call only one of the methods testCar.carAgeType or testCar.drivingTest they work fine when on there own but when called one after the other I get the exception. I am also unsure what to do when I use .hasNextLine and it comes back false.
Can anyone help me understand why Scanner throws an exception when it is called in multiple methods?
All help is much appreciated, thanks.
Code sample bellow has main and 2 classes, Vehicle parent and car child
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Would you like to test a used car today? : y or n");
if ("y".equals(scanner.nextLine())){
while (true) {
Car testCar = new Car();
testCar.drivingTest();
testCar.carAgeType();
break;
}
}else{
System.out.println("dang");
}
scanner.close();
}
}
import java.util.Scanner;
public class Vehicle {
private String licence, MOT;
public Vehicle(){
this("null", "null");
}
public Vehicle(String licence, String MOT) {
this.licence = licence;
this.MOT = MOT;
}
public String getLicence() {
return licence;
}
public String getMOT() {
return MOT;
}
public void drivingTest(){
Scanner DTScan = new Scanner (System.in);
System.out.println("great , do you have a driving licence :type: big, medium or small");
String reply = DTScan.nextLine();
if ("big".equals(reply) || "medium".equals(reply) || "small".equals(reply)) {
this.licence = reply;
} else {
this.licence = "fail";
}
System.out.println("Great you passed your '" + licence + "' exam. Lets check the MOT : type: pass or fail");
reply = DTScan.nextLine();
if ("pass".equals(reply) || "fail".equals(reply)) {
this.MOT = reply;
} else {
this.MOT = "invalid";
}
DTScan.close();
}
}
import java.util.Scanner;
public class Car extends Vehicle{
private String type;
private int age;
public Car(){
}
public Car(String licence, String MOT, String type, int age) {
super(licence, MOT);
this.type = type;
this.age = age;
}
public String getType() {
return type;
}
public int getAge() {
return age;
}
public void carAgeType(){
Scanner ATScan = new Scanner (System.in);
System.out.println("What type of car were you looking for :type: sports , town or 4X4");
ATScan.nextLine();
String reply = ATScan.nextLine();
if ("sports".equals(reply) || "town".equals(reply) || "4X4".equals(reply)) {
this.type = reply;
} else {
this.type = "invalid";
}
System.out.println("And what sort of Age :type: between 1 and 10");
int years = ATScan.nextInt();
if (years > 0 && years < 10) {
this.age = years;
} else {
this.age = -1;
}
ATScan.close();
}
}
class Main34 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Would you like to test a used car today? : y or n");
String val = scanner.nextLine();
if ("y".equals(val)) {
while (true) {
Car testCar = new Car();
testCar.drivingTest(scanner);
testCar.carAgeType(scanner);
break;
}
} else {
System.out.println("dang");
}
scanner.close();
}
}
class Vehicle {
private String licence, MOT;
public Vehicle() {
this("null", "null");
}
public Vehicle(String licence, String MOT) {
this.licence = licence;
this.MOT = MOT;
}
public String getLicence() {
return licence;
}
public String getMOT() {
return MOT;
}
public void drivingTest(Scanner scanner) {
System.out.println("great , do you have a driving licence :type: big, medium or small");
String reply = scanner.nextLine();
if ("big".equals(reply) || "medium".equals(reply) || "small".equals(reply)) {
this.licence = reply;
} else {
this.licence = "fail";
}
System.out.println("Great you passed your '" + licence + "' exam. Lets check the MOT : type: pass or fail");
reply = scanner.nextLine();
if ("pass".equals(reply) || "fail".equals(reply)) {
this.MOT = reply;
} else {
this.MOT = "invalid";
}
}
}
class Car extends Vehicle {
private String type;
private int age;
public Car() {
}
public Car(String licence, String MOT, String type, int age) {
super(licence, MOT);
this.type = type;
this.age = age;
}
public String getType() {
return type;
}
public int getAge() {
return age;
}
public void carAgeType(Scanner scanner) {
System.out.println("Enter age");
System.out.println("What type of car were you looking for :type: sports , town or 4X4");
String reply = scanner.next();
if ("sports".equals(reply) || "town".equals(reply) || "4X4".equals(reply)) {
this.type = reply;
} else {
this.type = "invalid";
}
System.out.println("And what sort of Age :type: between 1 and 10");
int years = scanner.nextInt();
if (years > 0 && years < 10) {
this.age = years;
} else {
this.age = -1;
}
}
}
Instead of creating Scanner object for every call, you just need to pass your existing scanner object to method.
Also instead of directly checking if ("y".equals(scanner.nextLine())) , you need to check using some variable like this if ("y".equals(val))
Try above code, it will work fine.
The problem comes from the fact that you use Scanner with System.in (which is a static InputStream). Whenever you call close() on a Scanner, it will automatically close the underlying InputStream, in this case System.in. Once System.in is closed, no other Scanner can read from it.
The solution to that problem is to don't close the Scanner in each of the functions and only do that in the main method.
From the Oracle documentation on the Scanner class:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
This means that when your first method closes the scanner, it closes also the input (System.in) and that's why you get the exception and also why calling only one method doesn't throw the exception.
Just close only the first scanner you have in your main and it should solve your issue.

Number of instances counter subclass

Eclipse keeps informing of an error when I try to implement a counter for a number of instances when called by the constructor. I've been searching on the matter, but the solutions are the exact thing eclipse won't let.
The problem is in Student() { count++; } in the subclass.
Implicit super constructor Dosije() is undefined. Must explicitly invoke another constructor
Main file
import java.util.Scanner;
public class TestDosije {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String jmbg=null;
System.out.println("ime osobe: ");
String ime= in.next();
System.out.println("prezime osobe: ");
String prezime= in.next();
System.out.println("jmbg: ");
while(!(Dosije.jesteJMBG(jmbg =in.next()) )) {
}
String ime_prezime= ime + " " + prezime;
Dosije dosije = new Dosije(ime_prezime, jmbg);
System.out.println(dosije.toString());
System.out.println("broj indeksa: ");
int index= in.nextInt();
System.out.println("godina upisa: ");
int upis= in.nextInt();
System.out.println("studije: ");
int studije= in.nextInt();
Student student = new Student(dosije, index, upis, studije);
System.out.println(student.toString());
System.out.println(student.getCount());
}
}
The superclass
public class Dosije {
private String ime_prezime;
private String jmbg;
public Dosije(String ime_prezime, String jmbg) {
this.ime_prezime=ime_prezime;
this.jmbg=jmbg;
}
public Dosije(final Dosije d) {
ime_prezime=d.ime_prezime;
jmbg=d.jmbg;
}
public String getImePrezime() { return ime_prezime; }
public void setImePrezime(String ime_prezime) { this.ime_prezime= ime_prezime;}
public String getJMBG() { return jmbg; }
public void setJMBG(String jmbg) { this.jmbg= jmbg;}
public String toString() {
return ime_prezime + "\njmbg: " + jmbg;
}
public static boolean jesteJMBG(String jmbg) {
if(jmbg.length() != 13) {
System.err.println("jmbg ima 13 cifara");
return false;
}
for(int i=0;i < jmbg.length(); i++) {
if(!(Character.isDigit(jmbg.charAt(i))) ) {
System.err.println("jmbg nije broj!");
return false;
}
}
return true;
}
}
The subclass of which instances I'm trying to count
public class Student extends Dosije{
private int br_index;
private int god_upis;
private int profil_studija;
private static int count=0;
Student() {
count++; //the devil himself
}
public Student(final Dosije d, int index, int upis, int studije){
super(d);
br_index=index;
god_upis=upis;
profil_studija=studije;
}
public Student(final Student s) {
super(s);
br_index=s.br_index;
god_upis=s.god_upis;
profil_studija=s.profil_studija;
}
public void setProfil(int n) {profil_studija=n;}
public int getCount() { return count; }
public String Studije(int i) {
if(i == 0)
return "Osnovne";
else if(i == 1)
return "MSc";
else
return "PhD";
}
public String toString() {
return super.toString() + "\n" + "broj indeksa: " + br_index + "/" + (god_upis % 100) + "\n"
+ "studije: " + Studije(profil_studija);
}
}
Your Student() constructor doesn't pass compilation since the super class doesn't have a parameterless constructor, so the implicit call to super(); added by the compiler doesn't pass compilation.
You can add a public Dosije() {} constructor to prevent that compilation error.
However, you might want to increment count in the other Student constructors too, in order to count the total number of instances created, regardless of which constructor was used.

I need to add a power up option where I can determine the value and select which superhero to give the value to

Here is what I have so far so as you can see I made a class for the powerup but I just keep getting stuck over and over again and ended up getting frustrated cause I couldn't figure it out myself.
public class Superhero {
private int heroStr;
public int powerUp;
private String name;
public Superhero(String name, int heroStr) {
this.name = name;
this.heroStr = heroStr;
System.out.println(name + " Strength is " + heroStr);
}
public Superhero(String name) {
this.name = name;
heroStr = 10;
System.out.println(name + " Strength is " + heroStr);
}
public int getStr() {
return heroStr;
}
public int powerUp(int powerUp) {
}
public static void main (String[] args) {
Superhero Gambit = new Superhero("Gambit");
Superhero Groot = new Superhero("Groot", 79);
}
}
Here you are:
public void powerUp(int powerUp){
//this.powerUp is the powerUp in your class, the powerUp without "this" is the powerUp given to the method
this.powerUp+=powerUp;
}
All you need now is to change your powerUp method:
public void powerUp(int powerUp) {
this.heroStr += powerUp;
}
and since you instantiated the superheroes, all you need is to call their methods, ex:
public static void main(String args[]){
SuperHero gambit = new SuperHero("Gambit",10);
gambit.powerUp(10);
System.out.println(gambit.getStr()); //should be 20
}
Also, as a side note:
the correct naming convention for variable names is:
Class object = new Class();

How to add in if else statement to validate for string

I am using BlueJ for this assignment I have and I have a problem doing this part of the question which is to put decision constructs to ensure that invalid data is not set which I have already tried.In which I placed the if else statement in
the setName portion which does not work. The code will show error if I have put 1 in the GraphicIllustrators main void portion for setName. So where do I need to put the if else statement in the code below.BTW I am using inheritance to do this.So please advise.Thanks!
The coding for the main class:
public class Publishing_Inc
{
private int ID=0;
private String name="-Name Needed-";
private int level=0;
private String jobtitle="-Title Needed-";
private String edit="-Edit Skill-";
public void calculateID(){
int uniqueID;
uniqueID =((int)( Math.random()*10000)+1);
ID = uniqueID;
}
public int getID(){
return ID;
}
public void setName(String d) {
name = d;
}
public String getName() {
return name;
}
public void setTitle(String b){
jobtitle=b;
}
public String getTitle() {
return jobtitle;
}
public void calculatelevel(){
int uniquelevel;
uniquelevel =((int)( Math.random()*3)+1);
level = uniquelevel;
}
public int getlevel() {
return level;
}
public void setEdit(String z){
edit=z;
}
public String getEdit() {
return edit;
}
}
The sub class:
public class GraphicIllustrators extends Publishing_Inc
{
public void displayGraphInformation() {
System.out.println("ID: " + getID());
System.out.println("Name:" + getName());
System.out.println("Job Title: " + getTitle());
System.out.println("Level: " + getlevel());
System.out.println();
}
public static void main (String args[]) {
GraphicIllustrators graphic = new GraphicIllustrators ( );
graphic.calculateID ( );
graphic.setName (" Tim Cook" );
graphic.calculatelevel ();
graphic.setTitle ("Graphic Illustrators" );
graphic.displayGraphInformation( );
}
}
public static void main (String args[]) {
GraphicIllustrators graphic = new GraphicIllustrators ( );
graphic.calculateID ( );
if (input instanceof String) {
graphic.setName ( input ); //where input comes from an input box or query or other source.
}
else
{
//alert the user.
}
graphic.calculatelevel ();
graphic.setTitle ("Graphic Illustrators" );
graphic.displayGraphInformation( );
}
When you pass an argument to the function setName that isn't a String, Java will throw an exception. You need to cast the object sent to a string. If you want to prevent this, you should check the input before it's send the function setName. This will check if the input is an instance of the Object String, if not alert the user.

Categories