Ok, so for my java class's final project we're supposed to implement a simplified version of craps that runs for 10 rounds. Whenever I run this, I get the NoSuchElementsException for the line "int b=std.nextInt()". Why is that? I opened a scanner object and whatnot, but it wont let me enter the data to proceed with the game, throwing the exception instead. I also get the same exception for the "System.out.println(now.toString());" line in the main method. How could that not have any elements?
public class Player {
private int bet;//how much was bet
private boolean Pass;//they chose pass
private boolean DPass;//they chose dont pass
private boolean win;//did they win?
private int money=20;//how much they have
//private String continuity="initial";
//Modifier methods
public void newBet(int x){this.bet=x;}
public void Pass(boolean x){this.Pass=x;}
public void DPass(boolean x){this.DPass=x;}
public void didYouWin(boolean x){this.win=x;}
public void newMoney(int x){this.money+=x;}
//public void keepPlaying(String s){this.continuity=s;}
//Accessor methods
public int getBet(){return this.bet;}
public boolean getPass(){return this.Pass;}
public boolean getDPass(){return DPass;}
public boolean getResult(){return this.win;}
public int getMoney(){return this.money;}
public boolean isWinning(){return this.win;}
//public String playing(){return continuity;}
public String toString(){
return "Bet: $"+this.bet+"\nBet on Pass: "+this.Pass+"\nBet on Don't Pass: "+this.DPass+"\nMoney:S"+this.money;
}
//Constructor method
public Player(int bet, boolean pass, boolean dpass){
this.bet=bet;
this.Pass=pass;
this.DPass=dpass;
}
}
Actual game play code<<<<<<<<<<<<<<<<<<<<<<<<<<
import java.util.*;
public class trial1 {
public static int RollDice(){ //Method for Dice Roll
int[] die1={1, 2, 3, 4, 5, 6};
int[] die2={1, 2, 3, 4, 5, 6};
Random r=new Random();
int i1=r.nextInt(6-0);
int i2=r.nextInt(6-0);
int sum=die1[i1]+die2[i2];
System.out.println("\nDie 1: "+die1[i1]+"\nDie 2: "+die2[i2]+"\nTotal Sum: "+sum);
return sum;
}
public static int Roll7(){//roll for 7
if (RollDice()==7){
return 2;
}
else return Roll7();
}
public static int PointRoll(int x){//If person rolled 4,5,6,8,9,10...
int a=RollDice();
if (a==x){
return Roll7();
}
else if (a==7){
return 1;
}
else return PointRoll(x);
}
public static int ComeOutRoll(){//1 = pass loses, 2 = pass wins, 3 = pass loses and dont pass gets nothing
int x=RollDice();
if ((x==2)||(x==3)) {
return 1;
}
else if ((x==7)||(x==11)){
return 2;
}
else if (x==12){
return 3;
}
else return PointRoll(x);
}
public static Player InitializeGame(){
//initialize stats and player
System.out.println("Please enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
Player name=new Player(b, betpass, betdpass);
System.out.print(name.toString());
std.close();
return name;
}
public static Player BeginGame(Player name){
//Start actual game process without the betting ie all the dice rolling and stat changing -->will return player's status
//boolean pass=name.getPass();
//boolean neutral=false;
int result=ComeOutRoll();
//find out if player won money or lost money
if (name.getPass()){//if player bet on pass
if (result==1){
name.newMoney(name.getMoney()-name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()+name.getBet());
}
else {
name.newMoney(name.getMoney()-name.getBet());
}
}
else {//if player bet dont pass
if (result==1){
name.newMoney(name.getMoney()+name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()-name.getBet());
}
else {
name.didYouWin(false);
}
}
if (name.getMoney()<=0){name.didYouWin(false);}//setting win data for yes or no. IF no money, u lose
else {name.didYouWin(true);}
public static Player Continue(Player name){//just like begin game, but adding the new bet
System.out.println("\nPlease enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
name.Pass(betpass);
name.DPass(betdpass);
name.newBet(b);
System.out.println(name.toString());
return BeginGame(name);
}
public static void Loss(Player name){//losing message
System.out.println("YOU LOSE!!!!!!!! HAHAHAHAHAHA!!!!!\n"+name.toString());
}
public static void End(Player name){//End game message
System.out.println("Thank you for playing!");
}
public static Player Run(){
Player name = InitializeGame();
return BeginGame(name);
}
public static void main(String[] args){
System.out.println("Welcome to my version of craps!");
Player now=Run();
for (int i=1;i<=10;i++){
if (now.isWinning()){
System.out.println("ROUND "+i);
System.out.println(now.toString());
now=Continue(now);
i++;
}
else {
Loss(now);
System.out.print(now.toString());
End(now);
i=11;
}
}
}
}
The NoSuchElementsException means that you tried to get an int from the scanner, std, but there was no next int. So it throws this error to let you know your input was bad.
It would seem from the NoSuchElementException that you're not reading an int from the Scanner. It is interpreting your input as some other data type.
Related
I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.
The goal of this code is to have a lockable interface for my main class, Coin, that makes the user input a key to access the main code. However, I have no idea on how to write the driver class in a way where the lockable object protects the regular methods (setKey, lock, and unlock) and when this object is locked, the methods cannot be invoked if it is unlocked it can be invoked. I have attempted a driver but it doesn't work.
package coins;
import java.util.Scanner;
public class Coins {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int guess;
System.out.println("Enter key: ");
guess = scan.nextInt();
Coin key = new Coin();
System.out.println(key);
final int flips = 1000;
int heads = 0, tails=0;
Coin myCoin = new Coin ();
for (int count =1; count <= flips; count++) {
myCoin.flip();
if (myCoin.isHeads())
heads++;
else
tails++;
}
System.out.println ("The number flips: " + flips);
System.out.println ("The number of heads: " + heads);
System.out.println ("The number of tails: " + tails);
}
}
Coin Class
package coins;
class Coin implements Lockable {
private final int HEADS = 0;
private final int TAILS = 1;
private boolean locked;
private int key;
private int face;
public Coin () {
flip();
locked = false;
key = 123;
}
public void flip() {
face = (int) (Math.random()*2);
}
public boolean isHeads() {
return (face == HEADS);
}
public String toString() {
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
public boolean locked(){
return locked;
}
public void setKey(int key){
this.key = key;
}
public void unlock(int key){
if(this.key == key){
locked = false ;
}
}
public void lock(int key){
if(this.key == key){
locked = true;
}
}
public void messageReturn(){
if(locked == false)
System.out.println("unlocked") ;
}
}
Lockable Interface
public interface Lockable {
public void setKey (int key);
public void lock (int key);
public void unlock (int key);
public boolean locked();
}
What Itamar Green is saying is true. However, to me, it appears that the real problem you are describing is in your Coins class, and not the Coin class. You aren't actually doing anything with the guess key that the user enters. You need to call setKey() on the Coin using that key. Then, your Coin will invoke or not invoke methods as per your code and Itamar's answer, by first checking to see whether it is in the locked state.
Firstly, you should check if the guess is correct via: (in main)
key.unlock(guess);//and you might want to set the default of locked to true, and remove the flip() in the constructor
You need to add a check in each method:
public void flip()
{
if(!locked)
face = (int) (Math.random()*2);
}
similarly with other methods.
Hi I'm currently doing this program for my assignment to create like a virtual shop. Currently I'm using NetBean IDE 8.1 and got an error when I tried to test the program. It's said , even though the program said build successful when I tried to build the program.
I did tried to follow the instruction in this video but came out empty image here
Here is my main program ( I haven't complete the program yet but this error keeps blocking me for testing it)
import java.util.Scanner;
public class Zarashop {
int choice;
public static void main(String[] args, int clothA){
Scanner absorb = new Scanner(System.in);
// phase 1 login
cloth cl = new cloth(); // declaring objects
payment pay = new payment();
personalinfo pi = new personalinfo();
shipping ship = new shipping();
receipt re = new receipt();
System.out.println("Welcome to Zara's cloth Shopping Center");
System.out.println("\nThis an online Shopping application will help you to buy "+ "a new cloth");
System.out.println("Please enter your detail");
System.out.println("\nPlease enter your name");
String Name = absorb.nextLine(); // user input name
System.out.println("\nAre you a student? (yes) or (no)");
String personalchoice = absorb.nextLine(); // user input status
//phase 2
System.out.println("please choose your cloth" );
System.out.println("cloth A detail : size: 170cm and red color ");
int cloathA = absorb.nextInt();
System.out.println("enter quantity ");
int quantity = absorb.nextInt();
pay.setclothA(clothA); // store value
pay.setquantity(quantity);
// phase 3 payment
System.out.println("please press 1 to calculate your payment");
int choice = absorb.nextInt();
if(choice == 1){
pay.total();
}
else {
System.err.println("error!");
}
}
}
Here is my main class for cloth ( misspelled was intended)
public class cloth {
// superclass
private int quantity; //
private int clothA=200;
//void
void setclothA(int ca){
clothA = ca;
}
void setquantity(int q){
quantity=q;
}
//get
int getclothA(){
return clothA;
}
int getquantity(){
return quantity;
}
}
my main class for personalInfo
public class personalinfo {
// superclass
public String Name;
private int Password;
private String TypeCard;
private int CardNo;
private String Address;
private int TeleNo;
//void
void setName(String n){
Name = n;
}
void setPassword(int p){
Password = p;
}
void setTypeCard(String tp){
TypeCard = tp;
}
void setCardNo ( int cn){
CardNo=cn;
}
void setAddress ( int a){
CardNo=a;
}
void setTeleNo ( int tl){
TeleNo=tl;
}
//get
String getName(){
return Name;
}
String getAddress(){
return Address;
}
int getPassword(){
return Password;
}
String getTypeCard(){
return TypeCard;
}
int getCardNo(){
return CardNo;
}
int getTeleNo (){
return TeleNo;
}
}
my sub class for payment
package zarashop;
//subclass
public class payment extends cloth {
String Status = "Initial";
public void total(){
int ca = super.getclothA(); //fetching values
int q = super. getquantity();
int total= q*ca;
}
}
public class receipt extends shipping{
}
my sub for shipping
public class shipping extends payment {
public int typeofshipping;
//void
void settypeofshipping(String ts){
String typeofshipping = ts;
}
int gettypeofshipping(){
return typeofshipping;
}
}
subclass for receipt (i'm reserving this for the program to display all the necessary user input)
public class receipt extends shipping{
}
thank you everyone and sorry for my bad program and my English.
A Java application can accept any number of arguments from the command line, and all of those are interpreted as String, that's why main only takes an array of String as parameter.
Change you code to
public static void main(String[] args)
and you'll be able to launch your application.
If you need to support a numeric command-line argument, you must convert a String argument that represents a number to an int:
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
parseInt throws a NumberFormatException if the format of args[0] isn't valid.
The example comes from official documentation.
Here is your mistake: public static void main(String[] args**, int clothA**)
Change it to public static void main(String[] args)
You will need to change your main method to public static void main(String[] args). By adding int clothA as a second argument, you are chaging the signature, and then it becomes an invalid main method to launch your application from.
If you want to retrieve something from console, you will find your argument inside args.
You can then retrieve clothA as follows:
int clothA;
if (args.length > 0) {
try {
clothA = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }
I'm building an application and i am trying to find a way to get data from one class to another class.
in my main class called Driver, i have a function which throws two dices and then i get a sum of them. This function is created in a class called Dices.
I have a new class called Players, where i need to get the data from the dice throw from my main class.
The code is the following
public class Player {
public String spillernavn;
public int pos;
public String SpillerNavn() {
return spillernavn;
}
public int move(int steps){
move=??;
pos=steps+pos;
return ??;
}
public int SpillerPos() {
return pos;
}
}
The Methode public int move(int steps){} is where i need to use the data from the dice throw and then make the addition with the pos, which stands for position.
The main function is the following
public static void main(String[] args) {
//Intializing dices
Dice die1 = new Dice();
Dice die2 = new Dice();
//Summ of dice
int sum = die1.throwDice() + die2.throwDice();
File name: Dice.java
import java.util.Random;
public class Dice {
private Random random;
public Dice() {
random = new Random();
}
public int throwDice() {
int num = 0;
while(num == 0) // Dice doesn't have a zero, so keep looping unless dice has a zero.
num = random.nextInt(7); // returns a random number between 0 - 6
return num;
}
}
File name: Players.java
public class Players {
private int sum;
public Players(int sum) {
this.sum = sum; // You got the data from `Driver class` here.
// You got the sum of two dice. Now do whatever you want to.
}
}
public class Driver {
public static void main(String[] args) {
Dice dye1 = new Dice();
Dice dye2 = new Dice();
int sum = dye1.throwDice() + dye2.throwDice();
Players player = new Player(sum); // Passing the data to Class Players
}
}
To send data, you need to pass the argument in the ()
You could do something like this.
public class Player {
public String spillernavn;
public int pos;
public String SpillerNavn() {
return spillernavn;
}
public int move(int steps, int move){
move=move;
pos=steps+pos;
return ??;
}
public int SpillerPos() {
return pos;
}
}
Then in main:
public static void main(String[] args) {
//Intializing dices
Dice die1 = new Dice();
Dice die2 = new Dice();
//Summ of dice
int sum = die1.throwDice() + die2.throwDice();
player.move(steps, move);
For future reference. You should probably create an instance of your dice in your player class. It's simple passing data between classes. Getters and setters.