Assignment:
Print person1's kids, apply the incNumKids() method, and print again, outputting text as below. End each line with newline.
Sample output for below program:
Kids: 3
New baby, kids now: 4
Code:
// ===== Code from file PersonInfo.java =====
public class PersonInfo {
private int numKids;
public void setNumKids(int personsKids) {
numKids = personsKids;
return;
}
public void incNumKids() {
numKids = numKids + 1;
return;
}
public int getNumKids() {
return numKids;
}
}
// ===== end =====
// ===== Code from file CallPersonInfo.java =====
public class CallPersonInfo {
public static void main (String [] args) {
PersonInfo person1 = new PersonInfo();
person1.setNumKids(3);
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
System.out.println("New baby, kids now: " + person1.getincNumKids());
return;
Problem:
I'm having trouble incrementing and including the incNumKids() method, and print again
Don't increment the number of kids within the println statement as it doesn't belong there -- it's not a statement that returns a String, but rather a method that changes the state of your PersonInfo object. Do it on its own on its own line, and then print the number of kids same as you did before, by calling getNumKids(). Also, don't call methods that simply don't exist, getincNumKids()??? There is no such method
public class CallPersonInfo {
public static void main (String [] args) {
PersonInfo person1 = new PersonInfo();
person1.setNumKids(3);
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
person1.incNumKids();
System.out.println("Kids: " + person1.getNumKids());
// return; // no reason for this
Heres what worked for me on the homework for my class
/* Your solution goes here */
System.out.println("Kids: " + person1.getNumKids());
person1.incNumKids();
System.out.println("New baby, kids now: " + person1.getNumKids());
Its the correct solution for the homework I am working on right now. Hope this helps you. Heres for peeps needing help with hmwk. x3
person1.setNumKids(personsKid);
int addOne;
addOne = personsKid + 1;
System.out.println("Kids: " + person1.getNumKids());
person1.setNumKids(addOne);
System.out.println("New baby, kids now: " + person1.getNumKids());
Related
so currently I m preparing for Oracle certified associate java...and I 've run to this question: what is the output of the following code
the solution says that s the output is: u u ucrcr
I know that static initializers only gets called once so
i don t get why the third u is printed
package com.company;
class Order {
static String result = "";
{
result += "c";
}
static {
result += "u";
}
{
result += "r";
}
}
public class Main {
public static void main(String[] args) {
System.out.print(Order.result + " ");
System.out.print(Order.result + " ");
new Order();
new Order();
System.out.print(Order.result + " ");
}
}
It outputs Order.result 3 times, that's why u is printed 3 times.
After the order class is loaded, result is u. You do System.out.print(Order.result + " "); to output it the first time, the you do System.out.print(Order.result + " "); to output it the second time. Then you create 2 instances of the Order class, thus appending "cr" twice, and how your result is ucrcr, so you output ucrcr, where you have your third you.
You must take into account the fact that System.out.print is being used here.
I am trying to create a program to keep track of College Teams and their sports records(Wins, Losses, years played). I want to use a Map(I opted for TreeMap) and a Set(I opted for TreeSet). I want to read the teams from a file and based on the input, update the database. For instance the line: 1975:UCLA:Brown would increment a win for UCLA, increment a loss of Brown and add the year 1975 to both teams.
The Key for the tree map will be the college names. the values is an object called TeamInfo
import java.util.TreeSet;
class TeamInfo {
int wins = 0;
int losses = 0;
TreeSet years;
TeamInfo(int wins, int losses, String year) {
// provide constructor code here
this.wins = wins;
this.losses = losses;
years = new TreeSet();
}
void incrementWins() {
wins++;
}
void incrementLosses() {
losses++;
}
void addYear(String aYear) {
// provide addYear code here
years.add(aYear);
}
public String toString() {
// provide toString() code here
return " Wins: " + wins + " Losses: " + losses + "\n" + "Years: " +
years.toString();
}
} // end TeamInfo
Ideally after reading from a file I should get the output:
Name: UCLA Wins:1 Losses:0
Name: Brown Wins:0 Losses: 1
My Problem comes when I have input like this:
1939:Villanova:Brown
1940:Brown:Villanova
1940:Brown:Villanova
I get output like this:
Name: Brown Wins: 2 Losses: 0
Years: [1940]
Name: Brown Wins: 0 Losses: 1
Years: [1939]
Name: Villanova Wins: 1 Losses: 1
Years: [1939, 1940]
Name: Villanova Wins: 0 Losses: 1
Years: [1940]
When the output should resemble:
Name:Brown Wins:2 Losses: 1
Name: Villanova Wins:1 Losses: 2
There are separate records for wins and losses for each team, when there should only be one record with both wins and losses. I've been staring at my code for hours and can't seem to see why it is doing that. Can anyone tell me what error I am committing and why this could be happening?
Thank You!
Here is my Main Class:
import java.util.TreeMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
public class Records {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
File input = new File("C:\\Users\\Christian\\Desktop\\C code\\input4.txt");
Scanner test = new Scanner(input).useDelimiter("[:\n]");
TeamInfo tester;
String year ="";
String winner="";
String loser="";
TreeMap records = new TreeMap();
TeamInfo temp = new TeamInfo(0,0,"");
while(test.hasNext())
{
year = test.next();
winner = test.next();
loser = test.next();
/*search(test.next)
increment win
*/
if(!records.containsKey(winner))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementWins();
firstRecord.addYear(year);
records.put(winner, firstRecord);
// System.out.println("First iteration of " + winner);
}
else if(records.containsKey(winner))
{
temp = (TeamInfo)records.get(winner);
temp.incrementWins();
temp.addYear(year);
records.replace(winner, temp);
// System.out.println("FOUND " + winner);
}
/*
search(test.next)*/
if(!records.containsKey(loser))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementLosses();
firstRecord.addYear(year);
records.put(loser, firstRecord);
// System.out.println("First iteration of " + loser);
}
else if(records.containsKey(loser))
{
temp = (TeamInfo)records.get(loser);
temp.incrementLosses();
temp.addYear(year);
records.replace(loser, temp);
// System.out.println("FOUND " + loser);
}
/*increment loss
*/
}
while(!records.isEmpty())
{
temp = (TeamInfo)records.get(records.firstKey());
System.out.println("Name: " + records.firstKey().toString() + temp.toString());
records.remove(records.firstKey());
}
}
}
I have a section of code that someone else wrote, and I cannot figure out how to make the code work with it.
I'm supposed to make a single Die roll and display a number between 1 and 6 using:
(int)(math.random()*6 + 1);
The code provided is this:
import java.util.*;
public class Ch3_PrExercise6
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Die die1 = new Die();
Die die2 = new Die();
System.out.println("die1: " + die1.getRoll()):
System.out.println("die2: " + die2.getRoll());
System.out.println("After rolling, die1: " + die1.rollDie());
System.out.println("After rolling, die2: " + die2.rollDie());
System.out.println("After second roll, die1: " + die1.rollDie());
System.out.println("After second roll, die2: " + die2.rollDie());
}
}
So far, all I can come up with is:
public class Die
{
//Sets initial value to 1
public int startFace
{
startFace = 1;
}
//Roll the die
public int rollDie
{
rollDie = (int)(math.random()*6 + 1);
}
}
I'm having trouble figuring out what the other program wants from me in the getRoll line. I understand that rollDie is called in the last four print commands.
I'm using Processing 2.20, If that's important.
I don't think that compiles? You're expecting rollDie to be a function, you can tell that because you have
die1.rollDie()
Note the parentheses: a function call.
so make a function and have it return a value:
public int rollDie()
{
int rollResult = (int)(math.random()*6 + 1);
return rollResult
}
I would upvote djna and accept his answer. To elaborate, I think this is all you need:
public class Die
{
private int face = 1;
// Get current value
public int getRoll () {
return face;
}
//Roll the die, return new value
public int rollDie () {
face = (int)(Math.random()*6 + 1);
return face;
}
}
I'm totally new to Java and I'm wondering why my static block is not executing.
public class Main {
public static void main(String[] args) {
Account firstAccount = new Account();
firstAccount.balance = 100;
Account.global = 200;
System.out.println("My Balance is : " + firstAccount.balance);
System.out.println("Global data : " + Account.global);
System.out.println("*******************");
Account secondAccount = new Account();
System.out.println("Second account balance :" + secondAccount.balance);
System.out.println("Second account global :" + Account.global);
Account.global=300;
System.out.println("Second account global :" + Account.global);
Account.add(); }
}
public class Account
{
int balance;
static int global;
void display()
{
System.out.println("Balance : " + balance);
System.out.println("Global data : " + global);
}
static // static block
{
System.out.println("Good Morning Michelle");
}
static void add()
{
System.out.println("Result of 2 + 3 " + (2+3));
System.out.println("Result of 2+3/4 " + (2+3/4));
}
public Account() {
super();
System.out.println("Constructor");
}
}
My output is:
Good Morning Michelle
Constructor
My Balance is : 100
Global data : 200
*******************
Constructor
Second account balance :0
Second account global :200
Second account global :300
Result of 2 + 3 5
Result of 2+3/4 2
I want to know why "Good Morning Michelle" was not displayed when I went in with the second account.
From the research I have done, this static block should execute each time the class is called (new Account).
Sorry for the real beginner question.
Michelle
Your static block that prints "Good Morning Michelle" is a static initializer. They are run only once per class, when that class is first referenced. Creating a second instance of the class will not cause it to run again.
Static blocks are executed the first time the Class is loaded. This is why you see the output once. Check out more details here: Understanding static blocks
This is a homework that I was working on. I have created 2 classes to play Towers of Hanoi. The first one is the basically a runner to run the actual game class.
import java.util.Scanner;
class TowersRunner {
public static void main(String[] args) {
TowersOfHanoi towers = new TowersOfHanoi();
towers.TowersOfHanoi()
}
}
public class TowersOfHanoi {
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
solve(num_of_discs, 'A', 'B', 'C');
}
public static void solve(int first_disc, char aTower, char bTower, char cTower) {
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower);
}
}
}
What I need help with is to make the TowersOfHanoi class to run from my TowersRunner class. I also need to implement a counter display how many times it took for the game to run until the game is finished in my TowersOfHanoi class. Basically I need line that is System.out.println("It took" + counter + "turns to finish.");
I don't know how to implement the counter correctly. Also, can't make the runner class to run the TowersOfHanoi. The TowersOfHanoi class runs fine by itself but the requirment for the homework is we need at least 2 classes min.
Help would be much appreciated!!! Please I am a novice in Java and programming in general please don't go too advanced on me. :D
You don't need the main-Function in the TowersOfHanoi class.
Instead, replace your TowersRunner main(String args[]) method with
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
TowersOfHanoi.solve(num_of_discs, 'A', 'B', 'C');
}
You can just pass the counter in the function and have it be incremented. For example:
public static void solve(int first_disc, char aTower, char bTower, char cTower, int counter) {
System.out.println("Currently on turn #" + counter);
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower, counter + 1);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower, counter + 1);
}
}
In the first call of solve, you would pass in 1. As you can see, each time solve is called recursively, the counter is incremented.
I'll leave you to adapt this to return the final value of counter :) If you just need the final value, you don't need to add a parameter at all. Just make the function return int instead of void then try and figure out how you would make it return the value you want.