I am working on a class assignment to get a coin to flip and record the amounts of times it lands on heads or tails. I am pretty sure most of this is right but the part that is throwing me off, is calling the method "coinFlip". when I try to call it in the counter class, I get the error message "coinFlip cannot be resolved to a type" I can't seem to figure out how to fix it, or grasp an understanding as to why I am getting that message. Any help is appreciated, thanks ahead of time.
package coinProject;
public class GenericCoin {
public class coinFlip{
private int heads = 0;
private int sideUp; //used to record which side the coin lands on
public coinFlip(){
flip();
}
public void flip(){
sideUp = (int) (Math.random() * 2);//used to keep random number under 2
}
public boolean headFlip(){
return (sideUp == heads);
}
public String toString(){//limits to only two print options, heads or tails
return (sideUp == heads) ? "Heads" : "Tails";
}
}
}
================================================================================
package coinProject;
public class counter {
public static void main(String[] args){
final int flip = 50;
int headFlips = 0 , tailFlips = 0;
coinFlip coin = new coinFlip();
for(int i = 1; i <= flip; i++){
coin.flip();
if(coin.headFlip()){
headFlips ++;
}
else{
tailFlips ++;
}
System.out.println(coin.toString());
}
System.out.println();//creates gaps after flips
System.out.println();
System.out.println("----- Flipped: " + flip);
System.out.println("----- Heads: " + headFlips);
System.out.println("----- Tails: " + tailFlips);
}
}
You have defined coinFlip as an inner class so you need an instance of GenericCoin before you can instantiate a `coinFlip'. So you need:
GenericCoin.coinFlip coin = new GenericCoin().new coinFlip();
Read the Oracle tutorial on nested classes: you need to define your coinFlip class as public static class coinFlip instead of public class coinFlip, the latter needing an instance of the enclosing class, as #user2341963 mentionned.
Related
I wrote this code in Eclipse Java and for some reason, it doesn't run. It doesn't say it has any errors in it and no red marks appear anywhere in the code. I'm not sure what is wrong with it, please help.
Here is the description of what I needed to write: Design and implement a class called PairOfDice, composed of two six-sided Die objects. Create a driver class called BoxCars with a main method that rolls a PairOfDice object 1000 times, counting the number of boxcars (two sixes) that occur.
public class dieGames {
public class PairOfDice {
private int die1;
private int die2;
public PairOfDice() {
roll();
}
public void roll() {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
}
public int getValueDie1() {
return die1;
}
public int getValueDie2() {
return die2;
}
public String toString() {
return "Die 1: " + die1 + ", Die 2: " + die2;
}
}
public class BoxCars
{
public void main(String[] args)
{
final int numRolls = 1000;
int numBoxCars = 0;
PairOfDice twoDice = new PairOfDice();
for (int i = 0; i < numRolls; i++)
{
twoDice.roll();
if (twoDice.die1 == 6 && twoDice.die2 == 6)
{
numBoxCars++;
}
}
System.out.println("Number of Box Cars in " + numRolls +
" rolls is " + numBoxCars);
}
}
}
A couple of things that I can see here:
you never create an instance of your diceGames class
your main method is not static, which is required
your main method is inside another class definition, which is also never instantiated
a couple of adjustments to your code make it run fine (commented in the code below):
// this class remains unchanged, except for making the PairOfDice class static
// so that it's accessible to the main method
public class dieGames {
public static class PairOfDice {
private int die1;
private int die2;
public PairOfDice() {
roll();
}
public void roll() {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
}
public int getValueDie1() {
return die1;
}
public int getValueDie2() {
return die2;
}
public String toString() {
return "Die 1: " + die1 + ", Die 2: " + die2;
}
}
// removed containing class, which was unnecessary
// made main method static
public static void main(String[] args)
{
// create an instance of the class
dieGames game = new dieGames();
final int numRolls = 1000;
int numBoxCars = 0;
PairOfDice twoDice = new PairOfDice();
for (int i = 0; i < numRolls; i++)
{
twoDice.roll();
if (twoDice.die1 == 6 && twoDice.die2 == 6)
{
numBoxCars++;
}
}
System.out.println("Number of Box Cars in " + numRolls +
" rolls is " + numBoxCars);
}
}
From this, I get output of Number of Box Cars in 1000 rolls is x, where x is some value depending on the run.
If you want to meet the assignment as you post it, the "driver class" BoxCars can be a separate .java file containing the main method:
public class BoxCars {
public static void main(String[] args)
{
final int numRolls = 1000;
int numBoxCars = 0;
PairOfDice twoDice = new PairOfDice();
for (int i = 0; i < numRolls; i++)
{
twoDice.roll();
if (twoDice.die1 == 6 && twoDice.die2 == 6)
{
numBoxCars++;
}
}
System.out.println("Number of Box Cars in " + numRolls +
" rolls is " + numBoxCars);
}
}
In this case, you'll need to either make a getter method for die1 and die2, or make them public in the first file, which should now just be the PairOfDice class without the enclosing dieGames class. Notice that this main method now instantiates PairOfDice and not dieGames, since that class isn't required.
This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 3 years ago.
my console doesn't seem to be showing any output on my projects, on some, it does at first. I am new to this so I don't understand it, this is an example of my code
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
}
public void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Replace your main method with the following code and it should work as you are expecting:
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
}
The reason why it didn't work for you is because you have missed to call the methods you have created in the class. I have added the following lines in the main method to complete that missing part:
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
None of your methods are static, so you'll need to create an instance of your TestAmazing class, and call methods via your instance.
That might look something like:
public static void main(String args[]) {
TestAmazing test = new TestAmazing();
test.roomtemp();
test.bonusball();
// etc...
}
Comment from QA:
this worked thank you! do I have to always do this and put it in the
same place? – Joe Emery
Not necessarily. It depends on the requirements of your program. If all of your methods are STATIC then you don't need an instance of your class. In that case, then you'd simply call all of your methods directly from main, like this:
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
roomtemp();
bonusball();
currentpopulationofchina();
gameloadingstatus()
}
public static void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public static void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public static void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public static void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Notice how every method has static in its declaration.
This question already has answers here:
Error in System.out.println
(5 answers)
Closed 4 years ago.
My Task:
Create a class called Icosahedron which will be used to represent a regular icosahedron, that is a convex polyhedron with 20 equilateral triangles as faces. The class should have the following features:
A private instance variable, edge, of type double, that holds the
edge
length.
A private static variable, count, of type int, that holds the
number of Icosahedron objects that have been created.
A constructor that takes one double argument which specifies the edge length.
An
instance method surface() which returns the surface area of the
icosahedron. This can be calculated using the formula 5*√3 edge².
An
instance method volume() which returns the volume of the icosahedron.
This can be calculated using the formula 5*(3+√5)/12*edge³.
An
instance method toString() which returns a string with the edge
length, surface area and volume as in the example below:
Icosahedron[edge= 3.000, surface= 77.942, volume= 58.906]
The numbers in this string should be in floating point format with a field
that is (at least) 7 characters wide and showing 3 decimal places.
Please use the static method String.format with a suitable formatting
string to achieve this. A static method getCount() which returns the
value of the static variable count.
Finally, add the following main method to your Icosahedron class so that it can be run and tested:
public static void main(String[] args) {
System.out.println("Number of Icosahedron objects created: " + getCount());
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++)
icos[i] = new Icosahedron(i+1);
for (int i = 0; i < icos.length; i++)
System.out.println(icos[i]);
System.out.println("Number of Icosahedron objects created: " + getCount());
}
Okay. so heres what i have started on:
import java.util.Scanner;
public class Icosahedron {
private double edge = 0;
private int count = 0;
Scanner input = new Scanner(System.in);
double useredge = input.nextDouble();
System.out.println("Enter Edge Length: ");
}
i receive an error on the last line. i cant use println() what am i doing wrong? or maybe im understanding the question wrong? any guidance would be appreciated.
thanks.
Your Icosahedron class should look like the following:
public class Icosahedron {
private double edge;
private int count;
public Icosahedron(int count) {
this.count = count;
}
public double getEdge() {
return edge;
}
public void setEdge(double edge) {
this.edge = edge;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Icosahedron{edge=" + edge + ", count=" + count + '}';
}
}
And your class containing the main method (I called it MoreProblem):
import java.util.Scanner;
public class MoreProblem {
public static void main(String[] args) {
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++) {
icos[i] = new Icosahedron(i+1);
Scanner input = new Scanner(System.in);
System.out.println("Enter Edge Length: ");
double userEdge = input.nextDouble();
icos[i].setEdge(userEdge);
}
for (Icosahedron icosahedron : icos) {
System.out.println(icosahedron);
}
System.out.println("Number of Icosahedron objects created: " + icos.length);
}
}
I'm a beginner in coding and wanted to train, and so I started doing exercises that I find on the internet, I finished one and was unsatisfied because of how easy it was, and created myself a challenge.
The exercise was: you type in a variable and it tells you if it is above a certain number, in this case it's 50, but here's the thing, I didn't want to type it in, I want it to be randomly generated, but I can't find a way to solve the problem, it blocks at nextInt.
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
random r = new random ();
int Low = 1;
int High = 60;
int mark = r.nextInt(High-Low)+ Low;
System.out.println("The mark is " + mark);
if (mark>50) {
System.out.println("PASS");
} else {
System.out.println("Fail");
}
}
private static class random {
public random() {
}
}
}
Use Java's Random class instead of defining your own private static class.
import java.util.Random;
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
Random r = new Random ();
int Low = 1;
int High = 60;
int mark = r.nextInt(High-Low)+ Low;
System.out.println("The mark is " + mark);
if (mark>50) {
System.out.println("PASS");
} else {
System.out.println("Fail");
}
}
}
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()