Java & NetBeans exercise, can't get it to work - java

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");
}
}
}

Related

I can not understand why my console is not showing any of my output [duplicate]

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.

Returning a value to another class and storing

Suppose given a class Die and it contains a random value for a six sided die.
Another class PairOfDice needs to access getvalue in Die and store two die values.
An error: cannot find symbol occurs when PairOfDice is executed.
How can this problem be fixed? And are there any other suggestions for the java code?
public class Die {
public static Random rand = new Random();
private int sides; // Number of sides
private int value; // Die's value
public Die() {
sides = 6;
roll();
}
public void roll() {
value = rand.nextInt(sides) + 1;
}
public int getSides() {
return sides;
}
public int getValue() {
return value;
}
The second class given is:
public class PairOfDice {
private int dieOne;
private int dieTwo;
public void main(String[] args){
Die die;
die = new Die();
}
private void dieOne(int value){
dieOne = die.getValue();
}
private void dieTwo(int value){
dieTwo = die.getValue();
}
public int getDieOneValue(){
return dieOne;
}
public int getDieTwoValue(){
return dieTwo;
}
}
This quest should be generalized:
I wrote the Die class with two public constructors. If the constructor is without the parameter, default size of die is six, else you can have any number of sides.
Then, I wrote the Dices class with two constructors. First one have the number of dices (with 6 sides), and second one have the List of dices with preferred sides.
If you want to learn how to generalize the problem (any problem) you can check my code. (Of course, it can be done more efficiently and with more elegance, but here is the simple code):
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Die {
private Random RAND = new Random();
private int noOfSides;
private int value;
// Default constructor without the parameter of sides gives the six sized die
public Die() {
this.noOfSides = 6;
}
// The constructor WITH number of sides
public Die(int noOfSides) {
this.noOfSides = noOfSides;
}
// rolling the die
public void roll() {
this.value = RAND.nextInt(noOfSides) + 1;
}
public int getValue() {
if (value == 0) roll(); // if the die is never rolled -> roll it!
// else return the rolled value
return value;
}
// just for curiosities
public int getNoOfSides() {
return noOfSides;
}
public String toString() {
return "Die has the " + noOfSides + " sides, and the last roll value was " + getValue();
}
}
class Dices {
private int noOfDices;
private List<Die> myDices = new ArrayList<Die>();
// NO constructor without the number of dices
private Dices() {
}
public Dices(int noOfDices) {
this.noOfDices = noOfDices;
// example is for 6 sided dices
for (int i = 0; i < noOfDices; i++) {
getMyDices().add(new Die());
}
}
// example with the list of dices with predefined sizes
public Dices(List<Die> myDices){
this.myDices = myDices;
}
public List<Die> getMyDices() {
return myDices;
}
public String toString() {
String s = "";
for (Die die : getMyDices()) {
s = s + die + "\n";
}
return s;
}
}
public class Answer {
public static void main(String[] args) {
//test with two dices (6 size):
Dices twoDices = new Dices(2);
System.out.println(twoDices);
//test with 4 dices size 3, 7, 9, 22
Dices fourDices = new Dices
(List.of(new Die(3),
new Die(7),
new Die(9),
new Die(22)));
System.out.println(fourDices);
}
}
You can see, if the die is never rolled, getValue first roll the die, then return the value. Otherwise you can roll the die and the value will be stored into the private field value...
We will presume that the Die class works as expected.
So, one could think of these changes to PairOfDice that likely resolve the immediate issue.
public class PairOfDice {
private Die dieOne = new Die();
private Die dieTwo = new Die();
public static void main(String[] args) {
PairOfDice pair = new PairOfDice();
System.out.printf("Pair: %d - %d%n", pair.getDieOneValue(), pair.getDieTwoValue());
}
public int getDieOneValue() {
dieOne.roll();
return dieOne.getValue();
}
public int getDieTwoValue() {
dieTwo.roll();
return dieTwo.getValue();
}
}
The PairOfDice class should hold references to two dice (in the private Die instance variables).
The getDieXValue() methods work with the instance variables, and return a value, after generating a roll().
Now, the question is whether the requirement is to store the values of two dice, or just access to the ability to get the values. If truly the need is to store the values, then one could do:
public class PairOfDice {
private int dieOneValue;
private int dieTwoValue;
public PairOfDice {
Die die = new Die();
// get a value for the first die
die.roll();
dieOneValue = die.getValue();
// get a value for the 2nd die
die.roll();
dieTwoValue = die.getValue();
}
public int getDieOneValue() {
return dieOneValue;
}
...
Personally, if one is going to create objects, then store and use the objects.

Why is my class variable rewriting itself after an unrelated method runs?

So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)

Error calling method

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.

Java Dice Game Trouble Generating new numbers

I am trying to learn OOP, starting with Java as I have read and been told it's the best place to start. With that said, I am trying to create a game for fun to help my learning, but I also know game programming and design can be more challenging.
So my goal here is to generate a new value from the RollDice D20 without having to reset or restart the program. You'll notice when I print out the values I print the same instance twice to demonstrate what I am avoiding, and a new instance to show that the new instance does indeed generate a new value. Perhaps, I am not approaching this in the right way, but this is a hurdle I am hoping to overcome with some help!
What I ultimately want is to figure out how to generate a new instance or at least a new roll value as many times as I want. Any and all help is greatly appreciated! I have added the code below as an example. Also any other feedback is appreciated.
import java.util.Random;
class RollDice
{// Begin RollDice Class
// Initiate method rollDice
public static int rollDice(int number, int nSides)
{
// System.out.println( "--- Welcome to the Dice Game v2! ---" ); //
// welcomes player
Random r = new Random();
// Declare class variables
int num = 0;
int roll = 0;
if (nSides >= 3)
{
for (int i = 0; i < number; i++)
{
roll = r.nextInt(nSides) + 1;
// System.out.println("Roll is: " + roll);
num = num + roll;
}
}
else
{
System.out.println("Error num needs to be from 3");
}
return num;
} // end method rollDice
int d4 = rollDice(1, 4);
int d6 = rollDice(1, 6);
int d8 = rollDice(1, 8);
int d10 = rollDice(1, 10);
int d12 = rollDice(1, 12);
int d20 = rollDice(1, 20);
public RollDice()
{
this.d4 = d4;
}
public void setD4(int D4)
{
this.d4 = D4;
}
public int getD4()
{
return d4;
}
// ////////////////
{
this.d6 = d6;
}
public void setD6(int D6)
{
this.d6 = D6;
}
public int getD6()
{
return d6;
}
// ////////////////
{
this.d8 = d8;
}
public void setD8(int D8)
{
this.d8 = D8;
}
public int getD8()
{
return d8;
}
// ////////////////
{
this.d10 = d10;
}
public void setD10(int D10)
{
this.d10 = D10;
}
public int getD10()
{
return d10;
}
// ////////////////
{
this.d12 = d12;
}
public void setD12(int D12)
{
this.d12 = D12;
}
public int getD12()
{
return d12;
}
// ////////////////
{
this.d20 = d20;
}
public void setD20(int D20)
{
this.d20 = D20;
}
public int getD20()
{
return d20;
}
// ////////////////
}// End RollDice Class
class Champion
{// Begin Champion Class
RollDice champDice = new RollDice();
int champroll = champDice.getD20();
public Champion()
{
this.champroll = champroll;
}
public void setChampRoll(int ChampRoll)
{
this.champroll = ChampRoll;
}
public int getChampRoll()
{
return champroll;
}
}// End Champion Class
public class DiceRollTest
{
public static void main(String ars[])
{
Champion tChampion = new Champion();
Champion pChampion = new Champion();
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + pChampion.getChampRoll() + "\n");
}
}
Your RollDice class is not accomplishing what you want. All it's doing is storing a single dice roll result for each type of dice you have. Therefore, when you go an call getChampRoll() on your Champion object, all it's doing is returning the roll that already took place when you constructed your RollDice class.
Instead, you should make rollDice() a member function of your RollDice class. RollDice should then take in its constructor an argument indicating which dice should be rolled when rollDice() is called. That way, when you call getD20(), it will roll the D20 and give you the result.
I'll leave you with this as a starting point:
import java.util.Random;
public class Die {
private int mSides;
private Random mRandom;
public Die(int sides) {
this.mSides = sides;
mRandom = new Random(System.currentTimeMillis());
}
public int roll() {
return mRandom.nextInt(mSides + 1);
}
public int roll(int times) {
int sum = 0;
for (int i = 0; i < times; i++) {
sum += roll();
}
return sum;
}
}
This class can be inherited/subclassed for each dice you want to create. Then you can toss a few of these in your champion's pockets :)
First, you should create new Constructor. In this constructor you should inicialize Random object, and probably how many sides will dice have
class RollDice{
Random rand;
int sides;
public RollDice(int x){
sides = x;
rand = new Random()
}
}
then, in that class you can add method which will generate new value
public int roll(){
return rand.nextInt(x);
}
you may as well don,t generate RollDice object with fixed value of dice's sides and make the method like:
public int roll(int x){
return rand.nextInt(x);
}
if you want java to generate new value after you enter something on console just use loop with System.in.read() and if or switch statement (for example if someone enters 1 - generate new value, if 0, end program)

Categories

Resources