Stack overflow error in main instantiating two objects? - java

Hello I'm still new to Java and OOP and am having issues trying to get my code to compile. I understand the issue with my code is the instantiation of the same object twice however I'm not sure how I can work around that to compile my code.
package week2;
import java.util.*
public class aBug {
aBug theBug = new aBug();
String Inspecies, Inname;
int Inx, Iny, Inenergy, Inid;
char Insymbol;
Scanner scan = new Scanner(System.in);
aWorld newWorld = new aWorld();
public static void main(String[] args) {
aBug theBug = new aBug();
theBug.mainMenu();
}
public void mainMenu() {
int choice;
do {
System.out.print("1\t Create bug\n");
System.out.print("2\t Enter world\n");
System.out.print("3\t Quit\n");
choice = scan.nextInt();
switch (choice) {
case 1:
bugInit();
break;
case 2:
System.out.println();
newWorld.mapInit(theBug.Inx, theBug.Iny, theBug.Insymbol);
System.out.println();
break;
}
} while (choice != 3);
}
public void bugInit() {
String species, name;
int x, y, energy, id;
char symbol;
System.out.print("Species: ");
species = scan.nextLine();
System.out.print("Name: ");
name = scan.nextLine();
System.out.print("X position: ");
x = scan.nextInt();
System.out.print("Y position: ");
y = scan.nextInt();
System.out.print("Energy: ");
energy = scan.nextInt();
System.out.print("ID: ");
id = scan.nextInt();
theBug.Insymbol = 'b';
theBug.Inspecies = species;
theBug.Inname = name;
theBug.Inx = x;
theBug.Iny = y;
theBug.Inenergy = energy;
theBug.Inid = id;
System.out
.format("\nThe bug is of the species %s, called %s, "
+ "with positions %d & %d, with energy amount: %d, and %d as it's id number\n\n",
theBug.Inspecies, theBug.Inname, theBug.Inx, theBug.Iny,
theBug.Inenergy, theBug.Inid);
}
}

In the constructor you have:
public class aBug {
aBug theBug = new aBug();
...
}
So while creating an instance of aBug (for example in your main) you call new aBug(), which calls the constructor again recurrently with out end overflowing the stack.
I am not sure why do you think you need to create an instance of the object within itself. So it's hard to give any hints. If I guess correctly, you merged the idea of aBug and "main program" in one class. You should split it and put aBug internal stuff in its own class.

Related

How do I create new objects in a switch

I'm new to Java and I am trying to create a program where you can sign up members to a club and i've hit a wall when trying to add / create people.
I can't seem to figure out how to keep creating new objects of a class inside an if statement or switch. (Like lets say going through the switch and adding 10 new members).
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("Opties: \n" +
"1) Add a member to the club.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
scanner.nextLine();
do{
switch(choice){
case 1:
System.out.println("New member name: ");
String newMemberName = scanner.nextLine();
System.out.println("New member age: ");
int newMemberAge = scanner.nextInt();
scanner.nextLine();
System.out.println("""
New member category:\s
A) Player
B) Coach""");
String categoryChoice = scanner.nextLine();
if (categoryChoice.equalsIgnoreCase("a")){
} else if(categoryChoice.equalsIgnoreCase("b")){
} else break;
case 2:
///temp
}
} while(choice != 3);
And this is the class + subclass
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Player extends Person {
public Player(String name, int age) {
super(name, age);
}
}
class Trainer extends Person {
public Trainer(String name, int age) {
super(name, age);
}
}
You should not create the variable inside an if statement, you should create the variable before hand with a default value null then change the variable's value inside each if statement with the proper object:
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("Opties: \n" +
"1) Add a member to the club.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
scanner.nextLine();
Person person = null; //needs to be the super class
do{
switch(choice){
case 1:
System.out.println("New member name: ");
String newMemberName = scanner.nextLine();
System.out.println("New member age: ");
int newMemberAge = scanner.nextInt();
scanner.nextLine();
System.out.println("""
New member category:\s
A) Player
B) Coach""");
String categoryChoice = scanner.nextLine();
if (categoryChoice.equalsIgnoreCase("a")){
person = new Player(newMemberName, newMemberAge);
} else if(categoryChoice.equalsIgnoreCase("b")){
person = new Trainer(newMemberName, newMemberAge);
} else break;
case 2:
///temp
}
} while(choice != 3);
}
Since you are creating objects inside a loop it would make more sense to create an ArrayList<Person> instead of a single variable and during each iteration you add a new object to it:
ArrayList<Person> people = new ArrayList<Person>(); //needs to be the super class - an empty list
do { ...
if (categoryChoice.equalsIgnoreCase("a")){
people.add(new Player(newMemberName, newMemberAge));
} else if(categoryChoice.equalsIgnoreCase("b")){
people.add(new Trainer(newMemberName, newMemberAge));
} else break;
} while(choice != 3);

Java exception running function listEmployee(): java.util.IllegalFormatConversionException

I'm very new to java and I can't figure out what it is I'm doing wrong, it's properly something really basic, I want to be able to add information about employees and then then display/list that data (id, first name, last name, salary, position etc ) using a menu() method.
Everything compiles and adding employee information with addEmployee() seems to work fine but when running listEmployees() I get the exception: java.util.IllegalFormatConversionException.
I have been playing around with it for a bit but I'm not getting anywhere, any help would be greatly appreciated.
import java.util.*;
public class Employee
{
final static int MAX=20;
static int [] idArray= new int[MAX];
static String [] firstnameArray= new String[MAX];
static String [] lastnameArray= new String[MAX];
static int count=0;
public static void add(int id, String fname, String lname)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter your id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)E
return;
System.out.println("Enter your First name");
String fname = sc.nextLine();
System.out.println("Enter your Last name");
String lname = sc.nextLine();
add(id, fname, lname);
}
}
public static void listEmployees()
{
for(int i=0; i<count; ++i)
{
System.out.printf("%-15s %10d \n",idArray[i],firstnameArray[i],lastnameArray[i] );
}
}
public static void printMenu()
{
System.out.println
(
"\n ==Menu==\n" +
"1. Add Employee\n"+
"2. Display Employee\n"+
"3. Quit\n"
);
}
public static void menu()
{
Scanner input = new Scanner(System.in);
int option = 0;
while(option!=3)
{
printMenu();
System.out.println("Please enter your choice");
option = input.nextInt();
switch(option)
{
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
break;
default:
System.out.println("Wrong option");
}
}
}
public static void main(String [] args)
{
menu();
}
}
You are passing a string (lastnameArray[i]) to a numeric format (%10d). You need to first convert the string lastnameArray[i] to an int/long and then pass that value to %10d.
System.out.println(idArray[i] + " " + firstnameArray[i] + " " + lastnameArray[i]);
use this one instaed of your printing statement
The printf function has the wrong arguments passed to it. You should match the format and parameters passed to print them in the same order. Assuming you are passing the correct parameter to be printed, the first parameter should have %d , %s , %s respectively.

Invoking method with array of objects as parameter

Hello I'm having issues running my method bugScan which I think is because I've declared myBugs as an array of objects. If any can give me any hints or point me the right direction of sorting this out I would very much appreciate it :) Below is all the appropriate classes:
package mainFuncs;
import java.util.Scanner;
public class aBug {
String species, name;
int x, y, energy, id, foodpref;
char symbol;
public void bugScan(aBug[] bugObjects, Scanner scan) {
String inSpecies, inName;
int inX, inY, inEnergy, inId;
for(int i = 0; i < bugObjects.length; i++)
{
System.out.print("Species: ");
inSpecies = scan.nextLine();
System.out.print("Name: ");
inName = scan.nextLine();
System.out.print("X position: ");
inX = scan.nextInt();
System.out.print("Y position: ");
inY = scan.nextInt();
System.out.print("Energy: ");
inEnergy = scan.nextInt();
System.out.print("ID: ");
inId = scan.nextInt();
bugObjects[i].symbol = '*';
bugObjects[i].species = inSpecies;
bugObjects[i].name = inName;
bugObjects[i].x = inX;
bugObjects[i].y = inY;
bugObjects[i].energy = inEnergy;
bugObjects[i].id = inId;
}
}
}
This is the other class:
package mainFuncs;
import java.util.Scanner;
public class mainMenu {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
aBug[] myBugs = new aBug[5];
myBugs.bugScan(myBugs, scan);
System.out.print("hi");
}
}
My issue is occurs at the line:
myBugs.bugScan(myBugs, scan);
with the error message "Cannot invoke bugScan(aBug[], Scanner) on the array type aBug[]"
You defined the method in the aBug class, but you trying to call it on an array of aBug objects! Anyway, I think you can take the bugScam method out from the first class and place it inside the second class.
package mainFuncs;
import java.util.Scanner;
public class aBug {
String species, name;
int x, y, energy, id, foodpref;
char symbol;
}
Second class:
package mainFuncs;
import java.util.Scanner;
public class mainMenu {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
aBug[] myBugs = new aBug[5];
bugScan(myBugs, scan);
System.out.print("hi");
}
public static void bugScan(aBug[] bugObjects, Scanner scan) {
String inSpecies, inName;
int inX, inY, inEnergy, inId;
for(int i = 0; i < bugObjects.length; i++)
{
System.out.print("Species: ");
inSpecies = scan.nextLine();
System.out.print("Name: ");
inName = scan.nextLine();
System.out.print("X position: ");
inX = scan.nextInt();
System.out.print("Y position: ");
inY = scan.nextInt();
System.out.print("Energy: ");
inEnergy = scan.nextInt();
System.out.print("ID: ");
inId = scan.nextInt();
bugObjects[i].symbol = '*';
bugObjects[i].species = inSpecies;
bugObjects[i].name = inName;
bugObjects[i].x = inX;
bugObjects[i].y = inY;
bugObjects[i].energy = inEnergy;
bugObjects[i].id = inId;
}
}
}
The typ parameter aBug will not be acceptable. By own written classes, the name should be written in camel case, so that could be the case of the exception.
the problem is with the line you mentioned!!
myBugs is an array and does not have any method bugScan
it should be something like this
new aScan().bugScan(myBugs, scan);
myBugs is an array, so you will only be able to perform array operations on it. Your method bugScan() is defined inside the aBug class. If you want to run it you can solve it by doing:
Bug tmp = new aBug();
tmp.bugScan(myBugs, scan);
But this smells like bad coding, the aBug class shouldn't have the responsibility the 'scan for bugs'.
On a side note: By convetion class names start with a capital and even if you apply the fix it will throw a NullPointerException because you never initialize your array.

Using default and non default constructors in my application

I'm new to java and have a question about default and non default constructors. My professor wants us to use the default constructor for creation of object BOOK1, and then use the non default constructor for BOOK2, BOOK3 and BOOK4. I know a constructor is used with the creation of an object, but I guess I don't understand how i'm supposed to differentiate between the two. My class code is as follows, where I have both a default and non default constructor:
import java.text.DecimalFormat;
public final class BOOKItem {
DecimalFormat intFormat = new DecimalFormat("000");
DecimalFormat doubleFormat = new DecimalFormat("$#,##0.00");
private int bookID;
private int numberInStock;
private double price;
private double totalValueOfStock;
private int code;
private String genre = "";
public BOOKItem() {
bookID = 0;
numberInStock = 0;
price = 0;
code = 0;
}
public BOOKItem(int newID, int newStock, double newPrice, int newCode) {
setID(newID);
setStock(newStock);
setCode(newCode);
setPrice(newPrice);
}
public void setStock (int newStock) {
if (newStock >= 1 && newStock <=5000) {
numberInStock = newStock;
}
else {
numberInStock = 0;
}
}
public void setCode (int newCode) {
if (newCode > 0) {
code = newCode;
}
}
public void setID (int newID) {
if (newID >=11 && newID <= 111111) {
bookID = newID;
}
else {
bookID = 0;
}
}
public void setPrice (double newPrice) {
if (newPrice >= 1.0 && newPrice <=150.0) {
price = newPrice;
}
else {
price = 0;
}
}
public int getID () {
return bookID;
}
public int getNumberInStock () {
return numberInStock;
}
public int getCode () {
return code;
}
public double getPrice () {
return price;
}
public double calcTotalValue () {
totalValueOfStock = numberInStock * price;
return totalValueOfStock;
}
public double getTotalValue () {
return totalValueOfStock;
}
public void display() {
switch (code)
{
case 1:
genre = "Romance";
break;
case 2:
genre = "Adventure";
break;
case 3:
genre = "Sci-Fi";
break;
case 4:
genre = "Mystery";
break;
}
System.out.println("Display:");
System.out.println("Book ID: " + bookID + " NumInStock: " + numberInStock + " Code: " + genre + " Price: " +
price + " TotalStockValue: " + calcTotalValue());
}
}
Here is my application that uses the constructors(sorry about the break in the class code, i dunno why its doing that):
import java.util.Scanner;
public class Project7 {
public static void main(String[] args) {
int bookID;
int numberInStock;
double price;
int code;
Scanner keyboard = new Scanner(System.in);
BOOKItem BOOK1, BOOK2, BOOK3, BOOK4;
BOOK1 = new BOOKItem();
BOOK2 = new BOOKItem();
BOOK3 = new BOOKItem();
BOOK4 = new BOOKItem();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD ID(<11 or >111111)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK1.setID(bookID);
BOOK1.setStock(numberInStock);
BOOK1.setCode(code);
BOOK1.setPrice(price);
BOOK1.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD STOCK(>5000)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2.setID(bookID);
BOOK2.setStock(numberInStock);
BOOK2.setCode(code);
BOOK2.setPrice(price);
BOOK2.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD PRICE(>150.0)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK3.setID(bookID);
BOOK3.setStock(numberInStock);
BOOK3.setCode(code);
BOOK3.setPrice(price);
BOOK3.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use ALL GOOD DATA");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK4.setID(bookID);
BOOK4.setStock(numberInStock);
BOOK4.setCode(code);
BOOK4.setPrice(price);
BOOK4.display();
}
}
Am I doing something incorrect with the creation of my objects? How do I use the non default constructor for BOOK2, BOOK3 and BOOK4? I created it, but perhaps i'm using it incorrectly. Any feedback would be greatly appreciated.
When you use
BOOK1 = new BOOKItem();
You are calling the default constructor (Construction without having any arguments)
After taking user input you would call the Non Default Constructor
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2 = new BOOKItem(bookID, numberInStock, price, code);
Use the above code to use the Parameterized Constructor (Non Default constructor)
This is called constructor overloading.
So for the objects you want to assign default values you call the default constructor
For the object you have information available with variables you sent them in the constructor that you have defined with parameters, To assign that value

Project on Imputing Weather Data

I keep getting the message
Exception in thread "main" java.lang.NoSuchMethodError: WeatherInput:
method ()V not found
in my client class for this project I'm working on and I'm not sure why, I was wondering if anyone here could see what I'm missing?
Here's my service class:
class WeatherInput
{
private static final String NEWLINE = "\n";
private double temp;
private double tempAverage;
private double tempHigh;
private double tempLow;
private double tempHundred;
public String newCity = new String();
public String city = new String();
public WeatherInput( String city) {
temp = 0;
tempAverage = 0;
tempHigh = 0;
tempLow = 0;
tempHundred = 0;
newCity = city;
}
public void setTemp( double temprature)
{
temp = temp;
}
public void tempCalc(String city)
{
while(!city.equals("*"))
{
city = newCity;
}
while(temp != 0)
{
tempAverage = (temp + temp)/2;
if(tempHigh > temp)
tempHigh = temp;
if(tempLow < temp)
tempLow = temp;
if(temp > 100)
tempHundred = temp;
temp++;
}
System.out.print(tempAverage);
}
public String printString(){
return NEWLINE + "Statistics for: " + newCity + "Average: " + tempAverage + "High: " + tempHigh + "Low: " + "Over 100: "
+ tempHundred + NEWLINE;
}
}
And this is my client:
import java.util.*; //For Scanner and class
//----------------------------------------------------------------------------------
//Class Name: KosmowsiProg2
//Description: This class has one method, the main method
//----------------------------------------------------------------------------------
public class KosmowskiProg2
{
//-------------------------------------------------------------------------------
//Method Name: main
//-------------------------------------------------------------------------------
public static void main(String[] args)
{
//-----------------------Local Constants--------------------------------------
//-----------------------Local Variables--------------------------------------
double newTemp;
//-----------------------Objects----------------------------------------------
Scanner scanner = new Scanner(System.in);
String city = new String();
String inputCity = new String();
WeatherInput input = new WeatherInput();
WeatherInput input2 = new WeatherInput();
//---------------------Method Body--------------------------------------------
System.out.print("Please enter the names of the cities, ending in a *");
inputCity = scanner.next();
System.out.print("Please enter the tempratures, ending in a 0");
newTemp = scanner.nextDouble();
input.setTemp(newTemp);
input.tempCalc(inputCity);
}//End main method
private static void printResults(WeatherInput in){
System.out.print(in.printString());
}
}//End class KosmowskiProg2
I'm creating a service class that I can then pass to a client class that will read a list of cities that ends in a "*" and then for each city read a list of tempratures that ends with a "0". It then has to calculate the average temperature, highest and lowest, and then output them along with any temperatures over 100. I've talked to my professor and she told me that the solution is a nested while loop, and that the prompts for the final program should be in a separate client class. I also need to output the totals for each category. The thing is, I'm having a lot of trouble trying to figure out how to use this service class I've created in the client to get the data I need. My professor can't seem to explain it in a way I can understand, so I'm hoping for some help.
WeatherInput requires a String as part of it's constructor...
public WeatherInput( String city)
But you're trying to insansiate it with out any...
WeatherInput input = new WeatherInput(); // This is bad, must have a String value...
If you have your service class in a different file, you need to make sure it's declared public.
public class WeatherInput
{
... etc
}
If you don't you may not be able to access the constructor in the other file.
EDIT: Oh, i just noticed, you don't have a default constructor (one with no arguments), which is why it throws the NoSuchMethodError exception. Your only constructor needs a city name:
public WeatherInput(String city) {
... etc
}
You'll need to declare your classes after you have the city names:
// WeatherInput input = new WeatherInput();
// WeatherInput input2 = new WeatherInput();
//---------------------Method Body--------------------------------------------
System.out.print("Please enter the names of the cities, ending in a *");
inputCity = scanner.next();
System.out.print("Please enter the tempratures, ending in a 0");
newTemp = scanner.nextDouble();
WeatherInput input = new WeatherInput(inputCity);
input.setTemp(newTemp);
input.tempCalc(inputCity);
Or create a constructor that doesn't take any arguments:
public WeatherInput() {
temp = 0;
tempAverage = 0;
tempHigh = 0;
tempLow = 0;
tempHundred = 0;
newCity = null;
}

Categories