I'm writing a code in JAVA that is going to be a Lucky Wheel Game. The game at this stage takes a number as input to start the wheel to turn, get a random element from a collection of prizes and outputs the price. As you can see the code below, I created an array and added it's elements to the ArrayList. The player have 3 turns and at each turn he gets a random price (element) from the ArrayList. Sounds good, but I'm stuck. The problem is, for some reason I get the error of "Cannot resolve symbol 'wheel'. I use IntelliJ IDEA. I just started coding so I'm sure there's gonna be more errors after I resolve this one. But first, I want to solve this, then I can continue the game and add more to it. Thanks for all the answers!
Here's the code:
import java.util.*;
public class Game {
public static void func1(String[] prizes) {
ArrayList<String> wheel = new ArrayList<>(5);
//Adds array elements to ArrayList
Collections.addAll(wheel, prizes);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
String[] prizes = {"Television", "iPhone", "Microwave", "Ventilator", "Gift Card"};
func1(prizes);
int turn = scanner.nextInt(1);
int tries = 0;
int index = randomGenerator.nextInt(wheel.size()); // I get the error here
//int wheel = wheel.size();
while(tries < 3) {
turn = scanner.nextInt(1);
System.out.println("You won a" + wheel.get(index)); // and here too
tries++;
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm still new to programming and I want to make a program that will take the food order from user until the user presses "n" to stop. But I can't seem to make it work like I want it to.
I want my output to be like this.
Buy food: Burger
Order again(Y/N)? y
Buy Food: Pizza
Order again(Y/N)? n
You ordered:
Burger
Pizza
But my output right now is this.
Buy food: Burger
Order again(Y/N)? y
Buy food: Pizza
Order again(Y/N)? n
You ordered:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Array.getFoodName()" because "food_arr2[i]" is null
at Food.main(Food.java:50)
Here is my code:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Food food = new Food();
Array[] food_arr;
boolean stop = false;
String foodName;
int k = 1;
int j = 0;
while(stop == false) {
food_arr = new Array[k];
System.out.print("Buy food: ");
foodName = s.next();
food_arr[j] = new Array(foodName);
food.setFoodArray(food_arr);
System.out.print("Order again(Y/N)? ");
String decide = s.next();
if(decide.equalsIgnoreCase("y")) {
k++;
j++;
}
else if(decide.equalsIgnoreCase("n")) {
stop = true;
}
}
Array[] food_arr2 = food.getFoodArray();
for (int i = 0; i < food_arr2.length; ++i) {
System.out.println("\nYou ordered: ");
System.out.println(food_arr2[i].getFoodName()); //This line is the error according to my output
}
}
I don't know how to fix this and I was hoping for someone to help me.
I think I see what you are trying to do with the k value setting the size of the array you are using.
However, with each iteration of the while loop:
food_arr = new Array[k];
Will create a new empty array each time!
So, for example, on the second iteration
food.setFoodArray(food_arr);
Will set foods array as something like [null, "Pizza"]
Even if this did work, creating a new array each time is not a very efficient method.
I would strongly recommend using a different, dynamically allocated data structure such as an ArrayList and defining it outside the scope of the while loop.
ArrayList<Food> food_arr = new ArrayList<Food>()
// Note that I'm just guessing the data type here - I can't see what you are actually using!
while(stop == false) {
System.out.print("Buy food: ");
foodName = s.next();
food_arr.add(foodName)
// etc, etc
}
food.setFoodArray(food_arr)
// ! Note: You will need to convert the array list into an array
// ! or change the data struture in the Food class
// etc, etc
However, this is just the first solution that popped into my head, check out different kinds of data structures and think about how else you could design this program yourself!
I am new to Java and am currently learning about random numbers. In my book it has a challenge activity to generate a random number between 100 - 149. Then it will automatically output 2 numbers and see if your code matches what they outputted. The code seems to work just fine, but my numbers are not matching. I was wondering what I could be doing wrong in my code?
import java.util.Scanner;
import java.util.Random;
public class RandomGenerateNumbers {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal;
seedVal = scnr.nextInt();
randGen.setSeed(seedVal);
seedVal = randGen.nextInt(50) + 100;
System.out.println(seedVal);
seedVal = randGen.nextInt(50) + 100;
System.out.println(seedVal);
}
}
The issue is that the code is producing what I would expect, it just does not match what the book is getting.
The book is using the value 102 and it is producing 113 and 124. My outputs are coming back as 112 and 102
I'm fairly new to java and am experimenting building my own text based game, at the moment im just trying to work on individual concepts and then hopefully be able to pull it all together in a final project, my problem i have come across at the moment and cant seem to find an answer is exactly what the title question states:
How can i validate user input against a String ArrayList of randomly generated elements?
To clarify, i have a working program at the moment that when run generates a random amount and random types of enemy and then populates them into the dungeon each time the dungeon object is created, the user is then presented with a question allowing them to pick which enemy they should confront first, this is where i require the validation in order that the game would continue, im trying to use a while loop which if the condition returns false would just skip and move on to if statements and their validations, i hope that makes sense and ive posted my code below, apologies in advance if there are many things wrong with my code either syntactically or structurally as stated earlier im still very new to java and at the moment if i can just learn to code then i can worry about how professional or proper something should be.
Here is my code:
package com.davegreen;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// Declaring some variables and creating some objects of other classes that i need.
Scanner scanner = new Scanner(System.in);
Dungeon dungeon = new Dungeon();
List<String> enemyType = dungeon.getEnemy(); // Gets all the enemy from my enemy ArrayList in the Dungeon class.
int enemyNumberTotal = dungeon.getEnemy().size(); // Gets the amount of enemy in my enemy ArrayList.
runGame();
int randomAmountOfEnemy = generateRandomNumber(enemyNumberTotal); // Generates a random amount of enemy into the dungeon from the total number in the ArrayList.
System.out.println("\n The enemies in this dungeon are: \n");
// Generates the random enemies that will populate the dungeon based on a method in my Dungeon class and then passes a random amount of said enemy each time also.
List<String> randomlyPickedEnemy = dungeon.populateWithRandomEnemy(enemyType, randomAmountOfEnemy);
System.out.println("\n\t * " + randomlyPickedEnemy);
System.out.println("\n> Which enemy would you like to confront first?");
String userChoice = scanner.nextLine();
// I want to validate the user input from line 31 of the code to reflect that if the user has not selected an enemy that was in the randomly populated list
// then we stay in the while loop and continue asking until of course the user types in a enemy that was in the randomly populated list, at which
// point we would of course skip the while loop moving onto the if statements validation, it would be nice also to have ignore case somewhere in there.
while(!userChoice.equals(randomlyPickedEnemy))
{
System.out.println("\n\t That enemy does not live in this dungeon!");
System.out.println("\n> Which enemy would you like to confront first?");
userChoice = scanner.nextLine();
}
// For the validation here i realise of course that just using the variable randomlyPickedEnemy in the sout would more than likely return ALL the enemy that
// were randomly populated and not specifically the enemy that the user had chosen, so at this point i need a way to be able to access exactly what enemy it was
// that the user had chosen to battle so that the sout statement makes sense but more importantly so i can then direct the code where it needs to go based on any given
// particular enemy.
if(userChoice.equals(randomlyPickedEnemy))
{
System.out.println("You have chose to battle " + randomlyPickedEnemy);
}
}
public static void runGame()
{
System.out.println("##################################################");
System.out.println("##### DUNGEON CRAWLER #####");
System.out.println("##################################################");
}
// This is my method to generate a random amount of enemy for the total amount of enemy in my ArrayList.
public static int generateRandomNumber(int howManyEnemies)
{
Random random = new Random();
int rng = random.nextInt(howManyEnemies) + 1;
System.out.println("\n There are " + rng + " enemies in this dungeon!");
return rng;
}
}
You are actually comparing a String to a List (randomlyPickedEnemy).
If I understand correctly, you want to know if this list contains the input of the user.
To do this you just have to modify your whilestatement :
while(!randomlyPickedEnemy.contains(userChoice)) {
...
}
can anyone tell me why I'm getting the error
Exception in thread "main" java.lang.NullPointerException
at test_package.First_class.main(First_class.java:14)
This is my code. it is designed to choose a random Parea and print it to the screen and then the Earea array in the same way. (please ignore the Areabase and the switch unless that is contributing to the error. Areabase is only there temporary)
package test_package;
import java.util.Scanner;
public class First_class {
private static final String[] Parea = null;
private static final String[] Earea = null;
public static void main(String[] args){
int Areabase = 1;
Scanner keyin = new Scanner(System.in);
switch (Areabase) {
case 1:
Parea[1] = "You enter what looks like it was once the ship cafateria but is now in ruin.";
Parea[2] = "You find yourself in a hallway, some of the lights are broken and the doors barely work.";
Parea[3] = "You enter an old storage room and almost slip into the huge hole that has opened up in the floor.";
Parea[4] = "You walk into the ships bathroom, the toilets are overflowing and the soap has a bite out of it.";
Parea[5] = "This seems to be an outdated controll deck, you wonder why it is here then you decide to move on.";
Parea[6] = "You emerge into the libary and almost trip over a stack of books. i lybrarian woould scream at this mess";
Parea[7] = "You find yourself in a room you dont reconise. there is glass all over the ground.";
Parea[8] = "You enter the main controll room. it seems that the entire front of the ship has colapsed.";
Parea[9] = "You walk into the ship's dorm. one room is littered with cat posters. Hang in there one says.";
Parea[10] = "This seems to have once been a black marketing room. you think you now understand the bounty.";
Parea[11] = "You emerge into a rapidly changing simulation room. it changes to a beach, a castle, YOUR SHIP?";
Parea[12] = "You move into the prisoner room. all the cells are open. people must have busted out.";
Parea[13] = "You trip and fall into the life support room. this room is badly dammage, badly badly dammages.";
Parea[14] = "You float into a random empty room. you emediatly know what it is. an anti gravity room.";
Parea[15] = "This room appears to be a half caved in engenerring room. maby you should leave befor those barrels explode.";
Earea[1] = "This room is on fire";
Earea[2] = "An explotion rocks the ship";
Earea[3] = "This room smells foul";
Earea[4] = "you wish you could take this room back to your ship";
Earea[5] = "THIS ROOM IS FILLED WITH ANIME";
int random = (int) Math.floor(Math.random() * (15 - 1) + 1);
int random2 = (int) Math.floor(Math.random() * (5 - 1) + 1);
System.out.println(Parea[random]);
System.out.println(Parea[random2]);
break;
default:
break;
}
}
}
Any ideas?
Thank you for your help :)
you have to set the length for the arrays first use them in Java
change these
private static final String[] Parea = null;
private static final String[] Earea = null;
to this
private static final String[] Parea = new String[16];
private static final String[] Earea = new String[6];
I've been working ahead in my intro class and I've almost finished my last project, Keno. its a betting game that rewards money according to how many numbers you matched with the dealer. I'm having issues on where to put the betting aspect, they start with 100$ and are asked to wage a certain amount of money. I don't know which method that would go under for it to still work because my methods aren't voids, so i wont be able to return more than one data value.
My second issue, maybe the more important one, is that they need to be unique numbers. To do that i would need to search the array of numbers every time to see if they match, or use an array of booleans to keep track of the numbers. I don't know how i would do the second but i have a good idea of what i would do with the first. The issue is that im using a do while already, im not sure how i could add the for loop with a nested for loop in. Here is my code, sorry if its messy, i know my teacher hates my curly braces:
package Keno;
import cs1.Keyboard;
public class Keno {
public static void main(String[]args){
int userArr[]=user();
int compArr[]=computer();
int howMany=matchNums(compArr,userArr);
int moneyGained=betting(howMany);
System.out.println("You matched "+howMany+" numbers");
System.out.println("You have gained "+moneyGained+" dollars!");
}
public static int[] computer(){
int []compChoice=new int[20];
for(int x=0;x<compChoice.length;x++){
compChoice[x]=(int)(Math.random()*81);
}
return compChoice;
}
public static int[] user(){
int choice[]=new int[7];
System.out.println("Welcome to Keno!");
System.out.println("Choose 7 unique numbers ranging from 1-80");
System.out.println("*************************************************");
//assigns numbers to choice array
for(int x=0;x<choice.length;x++){
do{
int temp=x+1;
System.out.println("number "+temp+": ");
choice[x]=Keyboard.readInt();
}while(choice[x]<0||choice[x]>80);
}
System.out.println("Thanks!");
System.out.println("*************************************************");
return choice;
}
public static int matchNums(int arr1[], int arr2[]){
int count=0;
//checks each array slot individually to see if they match
for(int x=0;x<arr1.length;x++){
for(int y=0;y<arr2.length;y++){
if(arr1[x]==arr2[y]){
count++;
}
}
}
return count;
}
public static int betting(int matches){
int moneyGained=0;
if(matches==7){
moneyGained=12000;
}else if(matches==6){
moneyGained=200;
}else if(matches==5){
moneyGained=20;
}else if(moneyGained==4){
moneyGained=1;
}
return moneyGained;
}
}
The simplest way to add the betting/money concept would be to add an integer which represents how much money the player has (starting at 100). You will have to ask the player how much they want to wager, and then adjust their money accordingly.
public static void main(String[] args) {
int playerMoney = 100;
int wagered = getWager(); // dont forget it has to be 0 < wagered <= 100
// adjust players money according to the wager, and how much they won
For ensuring uniqueness, either one of your ideas would work. I like just checking for the numbers existence already in the array, but the boolean array of size 80 would work too. It just seems like a lot for only 7 numbers though.