Randomly Throw Two Dice And Display Their Values

Mar 25, 2014

Dice are used in many games. One die can be thrown to randomly show a value from 1 through 6.

Design a Die class that can hold an integer data field for a value (from1 to 6).

Include a constructor that randomly assigns a value to a die object. Appendix D contains information on generating randomnumbers. To fully understand the process, you must learn more about Java classes and methods. However, for now, you can copy the following statement to generate a random number between 1 and 6 and assign it to a variable. Using this statement assumes you have assigned appropriate values to the static constants.

randomValue = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE +
LOWEST_DIE_VALUE);

Also include a method in the class to return a die's value. Save the class as

Die.java.

Write an application that randomly "throws" two dice and displays their values. After you read the chapter Making Decisions, you will be able to have the game determine the higher die. For now, just observe how the values change as you execute the program multiple times. Save the application as TwoDice.java.

View Replies


ADVERTISEMENT

Simulate Rolling Dice - Int Values Representation

Jan 20, 2015

import java.util.Random;
/**
* A very basic Dice that can be rolled and represent int values
*/

public class Dice{
private Random rand;
public Dice(){
rand=new Random();
}
/**simulates rolling the dice*/

[Code] ....

Why the Random rand is initiated at the Constructor and not at roll? Like the code works for both but I remember our teacher telling us something about one uses more memory than the other.

View Replies View Related

How To Randomly Assign Specific Values In Array Or ArrayList

Apr 3, 2015

I'm trying to build a monopoly like game, and atm I'm trying to find way how to build the Community and Chance chest cards. so far, my logic is

1-create an ArrayList of cards with a given order

2-for a given number of times(for loop) generate 2 random numbers ,which will be the parameters for Collection.swap().

3-swap.

here's the code for the shuffler Button

shuffler.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<shuffeledMessages.length;i++){
int randoma=(int)(Math.random()*4);
int randomb=(int)(Math.random()*4);
Collections.swap(myMessages,randoma,randomb);
}
}
});

For now things seem to work pretty ok, but I'm wondering if this is a good and efficient way to shuffle a card chest especially in case of large number of cards. plus, I'm not sure what would be a good loop count for effective shuffling, in my case I used i<arraylist.size

View Replies View Related

Display Result Of Two Dice Thrown Five Times And Total Of Those Results

Sep 12, 2014

I need to create a simply application that would display the results of two dice thrown five times and the total of those results. This is shown below in the attached file.

The problem is, I have a do-while loop that loops 6 times. Inside the loop, I have 2 random.nextInt(5) that generate random numbers. But how can I output the total? How can I make a variable equal to the sum of the two random numbers if the two random numbers are located inside a do-while loop?

Attached below is also the code I have thus far.

(Attached below is both files: what it needs to look like, and what it currently looks like)

View Replies View Related

Create For Loop That Randomly Assign Values To Each Element Within Array?

Apr 16, 2014

Started learning about Array's I'm doing an exercise where you create a for loop that randomly assigns values to each element within the array, but where is my code going wrong?

import java.util.Scanner;
public class ArrayExamples{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double exampleArray[] = new double[5];
System.out.print("Enter a Number: ");
int num1 = input.nextInt();

[Code] .....

View Replies View Related

Multi-sided Dice - Keep Track Of Total Sum Of All Dice In Array

May 7, 2014

I'm finishing up this assignment, and I'm stuck. These are the last 2 instructions:

. Roll each of the Dice by invoking the roll method on each Dice in the array.
. Keep track of the totals sum of all the dice in the array. Be sure to roll the dice array at least 10000 times.

How to finish it up?

Here's my code so far:

package homework3;

import java.util.Random;
public class Dice {
private int numberShowing;
private final int numberOfSides;
private static final Random randomNumber = new Random();
public Dice() {
numberOfSides = 6;

[Code] ....

View Replies View Related

Display Values In Fibonacci Sequence From F0 To F15

Apr 15, 2014

I am attempting a programming exercise to display the values in the Fibonacci sequence from F0 to F15. I understand the concept, but, for some reason my equation is simply creating a resulting string of numbers that simply increase by 2's. As, I know it is supposed to be the sum of the previous F and the F that precedes that one to total the new F number. It seems so simple yet I seem to be far off. As usual, I have worked my code for your review.

/*
* This program calculates the "Fibonacci sequence."
* A "sentinel" is used to limit the extent the calculation.
*/

import acm.program.*;
public class bookFibonacciTest2a extends ConsoleProgram {
/* Specifies the limit value of the calculations */
private static final int SENTINEL = 16;
public void run() {
println ("This program display Fibonacci sequence numbers 0 - 15.");

[Code] .....

View Replies View Related

How To Display Default Constructor Values

Sep 13, 2014

I am writing a program that accepts input from the user, I want default values displayed before the input values.

Java Code:

public surfboards() {
surfboardType = "Type not assigned";
shaperName = "Shaper not assigned";
constructionType = "Construction Type not assigned";
surboardSize = 0D;
} mh_sh_highlight_all('java');

I can get the output to display as shown below

(THIS IS WHERE I WANT DEFAULT CONSTRUCTOR DISPLAYED. Currently not displayed)

Type not assigned
Shaper not assigned
Construction Type not assigned
0 Feet

(THIS IS WHERE I WANT DEFAULT CONSTRUCTOR DISPLAYED. Currently not displayed)

input:

Java Code:
Enter Surboard Type:
test
Enter Shaper Name:
test
Enter Surfboard Construction Medium:
test
Enter Surfboard Size:
6.5 mh_sh_highlight_all('java');

Output:
test
test
test
6.5 feet

View Replies View Related

How To Get Values To Display One At A Time On New Lines

Feb 16, 2014

I am just displaying my values in different ways and I can't seem to get my values to display one at time on new lines. I dont know why that isn't compiling. The part i am having trouble with has the "Not Working" tag in the code.

[highlight=Java]
//Trying to figure out how to use /n
public class Test
{
public static void main(String[] args)
{
int gold= 5;
int silver= 3;
int bronze= 1;

[Code] ......

View Replies View Related

JSP :: How To Fetch Dynamic Values From Database And Display It

Dec 4, 2014

The program contains username and password which on submission checks with the database if the details entered are right or wrong....on right details it Displays Welcome (name) and (lastname) parameters from database.

View Replies View Related

JSP :: Dynamic Text Box - Display Values In Next Page

Mar 21, 2011

I am new to jsp .i created a wepage in jsp. That's i need to create dynamic textboxes in jsp and want to display the values of the textbox in next page.

View Replies View Related

Creates Two Die Objects And Roll Them Display The Values

May 4, 2014

I've written a die program, and i want the user to type any key in order to continue, how do i achieve this ?

I have already created a Die class, i just want to implement the main method now.

PHP Code:

package test;

/* This program demonstrates the use of a user-defined class

public class RollingDice {
// Creates two Die objects and rolls them display the values.
public static void main (String[] args) {
Die die1 = new Die();
System.out.println("Roll the die ")
}
} mh_sh_highlight_all('php');

What should i add after System.out.println, So that the user types (any key, or types "Enter" for example, for the die to roll). i dont want the die to roll by itself i Want the user to interact with the program in order for it to roll.

View Replies View Related

Reading File Input - Display All Values

Apr 8, 2014

I've been trying to learn how to read in file input and have a question about this piece of code:

Java Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class readFile {

public static void main(String args[]) throws FileNotFoundException{
File file = new File("file.txt");
int sum[]=new int[5];
int i=0;

[Code] .....

"file.txt" holds the following information:

1
2
88
42
56
89

But my output looks like:

2
42
89

if I take out sum[i]=input.nextInt(); it will display all values in the file.

View Replies View Related

JSF :: How To Convert Hashmap Values To Arraylist To Display On Page

Apr 2, 2015

I need assigning the selected hashmap values into a list and to display the values in a jsf page. The user will select certificates and will be stored in the below list:

private List<String> selectedCertificates = new ArrayList<String>();

The selectedCertificates will have the values ("AA","BB"). Now I will be passing the list into a hashmap in order to get the names and to display them on the jsf page.

My code is below:

Map<String, String> CertificatesNames =
new HashMap<String,String>(selectedCertificates.size());
CertificatesNames.put("AA", "Certificate A");
CertificatesNames.put("BB", "Certificate B");
CertificatesNames.put("CC", "Certificate C");
for(String key1: selectedCertificates) {
System.out.println(CertificatesNames.get(key1));
}

I want to display in my jsf page :

Certificate A
Certificate B

Now my issue is that is how to display all the values of the CertificatesNames.get(key1) in the jsf page as I tried to do the below and it printed all the values when I used the #{mybean.beans} using the :

List beans =
new ArrayList(CertificatesNames.values());

So how to do this?

View Replies View Related

Integer Values To Display In JFrame - RegEx Not Being Recognized

Jan 27, 2014

I have a program in which I am prompting users for integer values to display in a JFrame. I call the method below to load an array with their input:

Java Code:

public String inputAssembly(){
if (!jtfInput.getText().matches("d")){
JOptionPane.showMessageDialog(null, "Input must be of integer value.");
} if (jrbFar.isSelected()){
return jtfInput.getText() + jrbFar.getText();

[Code] ....

Regardless of the input, both messages display (invalid input / got it). I've tried debugging so I know that the values are getting entered and read correct, at least to my knowledge. It is a very simple regular expression, only checking to be sure an integer was entered.

View Replies View Related

JSF :: Display Values Of Selected Checkboxes On Page After Submitting Form

Feb 13, 2014

I have the following simple "selectManyCheckbox" specified in my jsf page:-

<h:selectManyCheckbox id="animalsmc" layout="pageDirection" value="#{animalSelectionBean.selectedAnimals}">
<f:selectItem itemValue="1" itemLabel="Lion"/>
<f:selectItem itemValue="2" itemLabel="Tiger"/>
<f:selectItem itemValue="3" itemLabel="Elephant"/>
<f:selectItem itemValue="4" itemLabel="Eagle"/>
<f:selectItem itemValue="5" itemLabel="kangaroo"/>
</h:selectManyCheckbox>

I have the following specified in my bean class:-

private int [] selectedAnimals;
...
public int[] getSelectedAnimals() {
return selectedAnimals;
}
public void setSelectedAnimals(int[] selectedAnimals) {
this.selectedAnimals = selectedAnimals;
}

I would like to know how to display the values of selected checkboxes on the JSF page after submitting the form? I tried outputtext, however it displays the object and not the values. I cannot even frame the outputformat for the same.

View Replies View Related

Program That Read Sequence Of Input Values And Display Bar Chart

Oct 21, 2014

Write a program that reads a sequence of input values and displays a bar chart of the values, using asterisks, like this:

********************** **************************************** **************************** ************************** **************

You may assume that all values are positive. First figure out the maximum value. That value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class Array717
{
public static void main( String[] args )

[Code] ....

The problem is that all this code does is print 1 line of *'s and what seems to be thousands of them

View Replies View Related

How To Throw Exceptions

Nov 22, 2014

I am just learning how to throw exceptions, and I'm stuck on the last part,

Here is where I created the exception that receives a string consisting of ID and wage.

public class EmployeeException extends Exception
{
public EmployeeException(String Employee)
{
super(Employee);
}
}

Here is where I created the Employee class with the two fields. I also believe I am throwing the exception if the hourly wage is < $6 or > $50.

public class Employee
{
int idNum;
double hourlyWage; 
public void Employee(int empID, double empWage) throws EmployeeException
{
idNum = empID;
hourlyWage = empWage;

[Code]...

Now, I need to write an application with three employees and display a message when an employee is successfully created or not. This is what I have so far... I'm trying to get it to work with one employee, and then I can easily go back and add two more.

import javax.swing.*;
public class ThrowEmployee
{
public static void main (String[] args)
{
try
{
Employee one = new Employee(542, 15.20);
}
 
[Code

The current compile error that I'm receiving is: ThrowEmployee.java:12: error: constructor Employee in class Employee cannot be applied to given types;

Employee one = new Employee(542, 15.20);
^
required: no arguments
found: int,double
reason: actual and formal argument lists differ in length
1 error

I have public void Employee(int empID, double empWage) in my Employee class, so why is it saying that no arguments are required? Not sure if I'm missing a step with throwing exceptions, because this error has always been a simple fix when I've come across it in the past?!?

View Replies View Related

How To Throw Exception

Mar 15, 2014

value1 = text1.getText();
value2 = text2.getText();
Connect c = new Connect(value1,value2);
if(c.check()== true)
{
Menu start = new Menu(c.getID());
dispose();

[code].....

I get an error "unreported exception java.SQLException; must be caught or declared to be thrown" how can i solve this I have taken a few basic classes but never got to exceptions.

View Replies View Related

How Many Exceptions Should A Method Throw At Most

Jul 31, 2014

There are times that my methods need to report the caller about many kinds of errors, represented as checked exceptions. This makes my methods look like very convoluted. It happens mostly when I work with stateless EJBs and databases. Sometimes I end throwing even 8 different exceptions! Are they too many?

Many of them inherit from common exceptions, so I've been tempted to throw the parent classes. But I've quickly discarded that option because I've read that it's a bad practice, since a method may throw only a subset of the children of that parent class, not all.

Finally, I've studied these possibilities:

1. Throwing the parent class (mentioned above).
2. Throwing a common exception with an error ID or code as message.
3. Throwing a common exception with an enum as member, as if it were an ID or code (safer than the #2).

All them show the same defect that the #1. However it's more a conceptual problem than a technical one, because my callers always use the same mechanism to treat every "specialization" of the same exception, without worrying about if the method really can return it or not.

View Replies View Related

Throw And Catch Error

Nov 7, 2014

public class ThrowException {
public static void main (String[] args) {
var x=prompt("Enter a number between 0 and 10:","");
try {
if (x>10){
throw "Err1";
} else if (x<0){
throw "Err2";
} else if (isNaN(x)){
throw "Err3";
}
}
catch(er){

[code]...

It's telling me where catch(er) is: <identifier> expected..I've watched videos, but no one seems to encounter this error....am I missing a segment of code?

View Replies View Related

Throw Exception In Overridden Method

Mar 19, 2015

I am practicing OCPJP ....

import java.lang.*;
class InvalidValueException extends IllegalArgumentException {}
class InvalidKeyException extends IllegalArgumentException {}
class BaseClass {
void foo() throws IllegalArgumentException {
throw new IllegalArgumentException();

[Code] .....

Which one of the following options correctly describes the behavior of this program? And the answer is (definitely) --> The program will print : InvalidKeyException exception, but when i saw the explanation, it tells

It is not necessary to provide an Exception thrown by a method when the method is overriding a method defined with an exception (using the throws clause).

I don't know, but i think it will compiled because the Exception that is thrown by the foo method in DeriDeri class is inherited from unchecked exception.. so it is not necessary to declare throws statement on its method.. and if the exception was checked exception the answer must be different right?

View Replies View Related

Interface With Buttons To Decide When To Throw 0 Or 1

Jun 10, 2014

imagine I build this this device that takes in impulses... 0 and 1..but I need an interface with buttons to decide when to throw a 0 or a 1...would java be a good language to control this?I'm having difficulty to make this path... interface to circuit...

View Replies View Related

Two Classes Compile Without Errors But When Try To Run They Throw Exceptions

Jan 24, 2015

numHitslocs

public class simpleDotCom {
int numHits=0;
int[] locationCells;
public void setlocationCells(int[] locs){
locs=locationCells;

[Code] ....

View Replies View Related

EJB / EE :: Entity And Mapped Superclass Throw Error - Has No Table In Database But Operation Requires It

Apr 16, 2014

I have a superclass used for all the other entity

@MappedSuperclass
public abstract class BssStandardEntityLaravel extends BssStandardEntity
implements InterfacciaBssStandardEntity, Cloneable{
private static final long serialVersionUID = 1L;
@Column(name = "created_at", nullable=true)
@Temporal(TemporalType.TIMESTAMP)
protected Date created_at = new Date();

[Code] ....

When i try to read some data with a JPA controller, this error is raised:

Persistent class "com.bss.libbssabstract.database.entity.BssStandardEntityLaravel" has no table in the database, but the operation requires it. Please check the specification of the MetaData for this class.
org.datanucleus.store.rdbms.exceptions.NoTableManagedException: Persistent class "com.bss.libbssabstract.database.entity.BssStandardEntityLaravel" has no table in the database, but the operation requires it. Please check the specification of the MetaData for this class.
at org.datanucleus.store.rdbms.RDBMSStoreManager.getDatastoreClass(RDBMSStoreManager.java:702)

[Code] ....

It requires BssStandardEntityLaravel table like a normal entity. I used the same entity package in other applications and it works perfectly. Why this error is raised?

I use jpa2.1.0 and datanucleus to enhance classes

View Replies View Related

JSP :: How Bank Sites Throw User To Session Expire Page By Clicking On Browser Refresh / Back Buttons

Jun 20, 2012

I got one task from my manager, regarding browser back button, refresh button. He asks me the web application has to work like Banks site... means if I refresh or click on Back button(Browser's) then it has to throw the user out of session, I checked lot in internet. But I found like only disabling back button of disabling F5 keys like that. But he’s not accepting that.

How to approach for this? Can we throw the user out of session when he clicks on browser back button or refresh button. I think its possible . But i don't know how to implement.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved