currently the program is listing the planets in a solar system. each planet entered to the solarsystem has a position counter adding position++
after all the planets are listed I want to SystemPrintln a statement saying, There are this many planets in your solar system. Should I not be able to just return position; for this?
At this point the result is in a toString so to add this final line stating the number of planets how would I do this?
Could I add a second method "position" to the toString?
can I just return position in a system.out.println statement from the drive class?
class Planet:
package planets;
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}
Class SolarSystem:
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString();
}
return result;
}
}
Class Driver:
package planets;
public class Driver {
public static void main(String[]args) {
Planet mercury = new Planet ("Mercury", 0);
Planet venus = new Planet ("Venus", 0);
Planet earth = new Planet ("Earth", 1);
Planet mars = new Planet ("Mars", 2);
Planet jupiter = new Planet ("Jupiter", 67);
Planet saturn = new Planet ("Saturn", 62);
Planet uranus = new Planet ("Uranus", 27);
Planet neptune = new Planet ("Neptune", 14);
Planet pluto = new Planet ("Pluto", 5);
SolarSystem solarSystem = new SolarSystem(9);
solarSystem.add(mercury);
solarSystem.add(venus);
solarSystem.add(earth);
solarSystem.add(mars);
solarSystem.add(jupiter);
solarSystem.add(saturn);
solarSystem.add(uranus);
solarSystem.add(neptune);
solarSystem.add(pluto);
System.out.println(solarSystem);
}
}
For your class you have to return the position variabel.
public int sumPlanets(){
return position;
}
and in your method toString use :
public String toString(){
return Integer.toString(sumPlanets());
}
but i recommend only use the position for return the total elements
public String toString(){
return position;
}
In your in your code :
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
return Integer.toString(sumPlanets());
}
public int sumPlanets(){
return position;
}
}
In order to print out the total number of planets I used the position variable which adds one each time a planets object is made.
position++
so to print this I added
System.out.println("You Have " + position + " Planets In Your Solar System");
Directly after the loop so It would be printed out one time with the total amount.
The full class ended up like this.
package planets;
public class SolarSystem {
private Planet[]planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString();
}
System.out.println("You Have " + position + " Planets In Your Solar System");
return result;
}
}
Related
When I run the below code I can not get it to give me a positive result. I can get this code to run, but once I add the binary search portion of the code, it keeps telling me my value is not in the list. And I know the value is on the list. Can someone please tell me what I did wrong? I want it to tell me the house value and the year of that value. Any help will be much appreciated.
import javax.swing.JOptionPane;
import java.util.*;
import java.util.Arrays;
static class House implements Comparable<House> {
private int price;
private int year;
public House(int price, int year) {
this.price = price;
this.year = year;
}
public int getPrice() {
return price;
}
public int getYear() {
return year;
}
#Override
public String toString() {
return "{" + "Price='" + price + '\'' +
", Year=" + year + '}';
}
#Override
public int compareTo(House o) {
if (this.year != o.getYear()) {
return this.year - o.getYear();
}
return this.price;
}
}
public static void main(String[] args)
{
BinarySearch ob = new BinarySearch();
House[] house = { new House(85480, 2013), new House(98873, 2012), new House(150592, 2022), new House(98035, 2014),
new House(114730, 2017), new House(178124, 2023), new House(137676, 2019),new House(104548, 2015),
new House(151330, 2021), new House(114730, 2016), new House(144452, 2020), new House(121614, 2018)};
System.out.println("Original Array of House objects:");
System.out.println(Arrays.toString(house));
Arrays.sort(house);
System.out.println("\nSorted Array of House objects:");
System.out.println(Arrays.toString(house));
String input = JOptionPane.showInputDialog("What house value do you want to search for: ");
int input2=Integer.parseInt(input);
int x = input2;
int result = ob.binarySearch(house, x);
if (result == -1)
{
JOptionPane.showMessageDialog(null, "The house value you are looking for is not in the list. ");
}
else
{
JOptionPane.showMessageDialog(null, "The house value is " + x + " year = " + "index " + result);
}
}
static class BinarySearch
{
int binarySearch(House[] house, int x)
{
int left = 0, right = house.length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (house.length == x)
return mid;
if (house.length < x)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
}
}
I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class JavaClass {
public static void main(String[] args) {
// Things start here
int[][] multi = new int[5][10];
for(int p = 1; p < 5; p++)
{
for(int h = 1;h < 10;h++)
{
System.out.println("Enter the score for Player " + String.valueOf(p) + ", Hole " + String.valueOf(h) + " :");
String v = stringReader();
multi[p][h] = Integer.parseInt(v);
System.out.println(String.valueOf(v));
}
}
}
public static String stringReader()
{
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
value = bufferedReader.readLine();
} catch (IOException e) {
value = "0";
}
return value;
}
Hello! I am currently working on a project for my Grade 12 Computer Science course where i am asked to make a "Golf Score Tracker" the description of the project is (add to the code below code that calculates and displays each golfers individual score)
I've tried working with while loops however whatever I do it does not seem to display. My teacher is also stuck lol he is actually the reason I am here asking for help on this project
I have to make a graphical representation of a binary tree with the possibility of selecting nodes...Any ideas?
It should look like this
binary tree
I might translate this later for a quick, working example in C#, but here is a Java homework assignment I did way back in 2000!
You should be able to glean the algorithm and code necessary to draw the Tree based on the Java class:
// FileName: DrawBinaryTree.java
/************************************
* Student: Michael Tomlinson *
* Course: CS 145-Section 1 *
* Instructor: Dareleen Schaffer *
* *
* Assignment #4, Problem #1 *
* Due Date: July 24, 2000 *
************************************
*/
package BinaryTree;
import java.awt.*;
import javax.swing.*;
public class DrawBinaryTree {
// Data Fields
private BinaryTree tree=null;
private double xDiv=50, yDiv=50;
private boolean sizeToFit=true;
private Panel outputPanel=null;
// Constructors
public DrawBinaryTree() {} // default constructor
public DrawBinaryTree(BinaryTree tree) {
setBinaryTree(tree);
} // end constructor with (BinaryTree) parameters
public DrawBinaryTree(Panel panel) {
setOutputPanel(panel);
} // end constructor with (JPanel) parameters
public DrawBinaryTree(BinaryTree tree, Panel panel) {
setBinaryTree(tree);
setOutputPanel(panel);
} // end constructor with (BinaryTree, JPanel) parameters
// Modifiers
public void setBinaryTree(BinaryTree tree) {
this.tree = tree;
} // end method setBinaryTree
public void setOutputPanel(Panel panel) {
this.outputPanel = panel;
} // end method setOutputPanel
public void setSizeToFit(boolean sizeToFit) {
this.sizeToFit = sizeToFit;
} // end method setSizeToFit
public void increaseXDiv() {
xDiv*=1.1;
} // end method increaseXDiv
public void increaseYDiv() {
yDiv*=1.1;
} // end method increaseYDiv
public void decreaseXDiv() {
xDiv*=.9;
} // end method decreaseXDiv
public void decreaseYDiv() {
yDiv*=.9;
} // end method decreaseyDiv
// Public Methods
public void drawTree(Point translate) {
if(outputPanel!=null && tree!=null) {
Graphics g = outputPanel.getGraphics();
g.translate(translate.x, translate.y);
Dimension panelSize = outputPanel.getSize();
if(!tree.isEmpty()) {
int treeDepth = tree.maxLevel();
if(sizeToFit) {
xDiv = (double)panelSize.width/(Math.pow(2,treeDepth+1)+1);
yDiv = (double)panelSize.height/((double)treeDepth+1);
}
Point rootCoord = new Point(panelSize.width/2, (int)(yDiv/2));
drawTreeNode(rootCoord, tree.getRoot(), 0, g);
}
else {
Font f = g.getFont();
String message = "The Tree is Empty.";
FontMetrics fm = g.getFontMetrics(f);
int messageLength = fm.stringWidth(message);
int messageHeight = fm.getHeight();
g.drawString(message, panelSize.width/2 - messageLength/2,
panelSize.height/2 - messageHeight/2);
}
g.dispose();
}
} // end method drawTree
// Private Methods
private void drawTreeNode(Point coord, SearchTreeNode node, int depth,
Graphics g) {
double xOffset = (Math.pow(2, tree.maxLevel() - depth)/2)*xDiv;
int newY =(int)(((double)depth+1)*yDiv+yDiv/2.0);
if(node.leftChild!=null) {
int lcx = (int)(coord.x - xOffset);
g.setColor(Color.blue);
g.drawLine(coord.x, coord.y, lcx, newY);
Point leftChildCoord = new Point(lcx, newY);
drawTreeNode(leftChildCoord, node.leftChild, (depth + 1), g);
}
if(node.rightChild!=null) {
int rcx = (int)(coord.x + xOffset);
g.setColor(Color.red);
g.drawLine(coord.x, coord.y, rcx, newY);
Point rightChildCoord = new Point(rcx, newY);
drawTreeNode(rightChildCoord, node.rightChild, (depth + 1), g);
}
g.setColor(Color.black);
g.drawOval(coord.x-5, coord.y-5, 10, 10);
g.fillOval(coord.x-5, coord.y-5, 10, 10);
g.drawString(node.item.toString(), coord.x+10, coord.y+5);
} // end method drawTreeNode
} // end class DrawBinary Tree
I have an array with 5 elements. If a user inputs a name or a title, it should output that person's or job title's corresponding job title and person. Here's what I got, I'm not sure what I could be doing wrong. Since it's an applet, I don't need a main method right? Did I get stuff mixed up? What could I be doing wrong? Even if I input data that is stored in the array, it always gives me "input did not match any records" I would appreciate any help. Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment extends JApplet implements ActionListener
{
String[] empName = {"John Jacobs" , "Will Watts","Kevin Krust", "Allan Ayers", "Sam Smith"};
String[] empTitle = {"Software Engineer" , "Database Administrator", "Network Administrator" , "Head Programmer" ,"Department Manager"};
final int ARRAY_SIZE = 5;
boolean validName = false;
boolean validTitle = false;
String nameOfEmployee;
String titleOfEmployee;
JLabel enterInfo = new JLabel("Enter an Employee Name or Job Title");
JTextField userInput = new JTextField(20);
JButton empButton = new JButton ("Press if you entered a name");
JButton titleButton = new JButton ("Press if you entered a title");
JLabel inputDisplay = new JLabel("");
Container con = getContentPane();
public void init()
{
con.add(enterInfo);
con.add(userInput);
con.add(empButton);
con.add(titleButton);
con.setLayout(new FlowLayout());
userInput.addActionListener(this);
empButton.addActionListener(this);
titleButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == empButton)
{
String nameEmp = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameEmp == empName[x])
{
validName = true;
titleOfEmployee = empTitle[x];
}
}
if(validName)
inputDisplay.setText(nameEmp + "is a" + titleOfEmployee);
else
inputDisplay.setText("The title you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
else
{
String nameJob = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameJob == empTitle[x])
{
validTitle = true;
nameOfEmployee = empName[x];
}
}
if(validName)
inputDisplay.setText(nameOfEmployee + "is a" + nameJob);
else
inputDisplay.setText("The name you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
con.invalidate();
con.validate();
}
}
This
nameEmp == empName[x]
compares object references. What you want is comparison of contents, so you should check
nameEmp.equals(empName[x])
When comparing the value input by the user to the values in your arrays, you need to use the equals function and not ==.
Read why here.