Loop not recognizing variables previously defined - java

I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}

All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}

public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.

public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!

Related

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

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.)

'.class error' in java

Hi there I am super new to coding and I keep getting a '.class' error when I try to run the code below. What am I missing?
import java.util.Scanner;
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
userWeight = new int[5];
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight = scnr.nextInt[];
return;
}
}
This is the problem
userWeight = scnr.nextInt[];
Solve this by:
userWeight[0] = scnr.nextInt(); //If you intended to change the first weight
OR
userWeight[1] = scnr.nextInt(); //If you intended to change the value of userWeight at index 1 (ie. the second userWeight)
Should work
PS: As a precaution do not import the Scanner class twice. Doing it once would be enough
I understood your intension and below are two possible ways to implement your thought:
I see you are giving values manually as userWeight[0]=0;
If you wanna give manually I suggest not to go with scanner as below.
public static void main(String[] args) {
int[] userWeight={0, 5, 6,7,9};
System.out.println("Weights are" +userWeight);//as you are giving values.
}
If your intension is to get values at run time or from user, please follow below approach
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("This is runtime and you need to enter input");
int[] userWeight = new int[5];
for (int i= 0; i < userWeight.length; i++) {
userWeight[i] = sc.nextInt();
System.out.println(userWeight[i]);
}
}
PS:
I seen you are using util package import for two times, instead you may import all at once as import java.util.*;
Also you are trying to return. Please note for void methods its not need for return values. VOID excepts nothing in return.
First of all do not import packages more than once, now lets go to the actual "bugs".
Here:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userWeight[] = new int[5];//You need to declare the type
//of a variable, in this case its int name[]
//because its an array of ints
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight[0] = scnr.nextInt();//I belive that you wanted to change
// the first element of the array here.
//Also nextInt() is a method you can't use nextInt[]
//since it doesn't exists
//return; You dont need it, because the method is void, thus it doesnt have to return anything.
}
}
Also instead of this:
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
you can do this during the declaration of an array:
int userWeight[] = {0,5,6,7,9};//instantiate it with 5 integers

How to pass an array and an int trough classes and methods?

I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
This is my main method -
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = methods.createBoard();
userInput = methods.input();
}
}
And this is my methods class -
import java.util.Scanner;
public class methods {
//Create board method
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
//Take a guess method
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes and methods therefore I create lots of them.
You'll have to create a new instance of Main and methods first or alternatively declare the createBoard() and input() methods static.
Here is the code snippet:
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.run();
}
private void run() {
methods me = new methods();
int[] playBoard = me.createBoard();
int userInput = me.input();
}
}
Also, as per the naming convention rules for the class name it should be Methods instead of methods.
You haven't declared the variable playBoard being used inside Main. Did you intend to use board2 instead. I guess you want something like below:
board2 = new methods().createBoard();
userInput = new methods().input();
You need to create an object of class methods, in order to access instance methods.

Setting values to parameters in a constructor in Java

I just wanted to ask basically what the title says. Here's my example and I want x to be the new set random. I also am doing this off a phone switch doesn't support an equal sign so - means equal. Also the bracket is (. So when I do
Constructor a - new Constructor(x)
public class Opponent (
public static x - 0;
public Opponent (int value) (
value - 5;
)
public static void main (String() args) (
Opponent character1 - new Opponent(x)
System.out.println(x);
)
)
Basically I want x to become 5. The game I am developing concerns randomization then the values should give them to the parameter to the newly created character.
Problem I am having is that its not working which means it probably can't do this.
Is there anyway I can do this.
I apologize if it is a dumb question though but anyways thanks.
public class Opponent {
public static int x = 0;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
int y = 5; // random number I chose to be 5
Opponent character1 = new Opponent(y);
System.out.println(character1.x + ""); // will display 5 (which was int y)
}
}
List of Problems:
• To open/close a method/class, don't use ( and ); you have to use { and }
• public static void main (String() args) needs to be public static void main (String[] args)
• To initialize something, use =, not -.
• You need to give x a type, such as int.
• When you defined Opponent character1 - new Opponent(x), you need to have a semi-colon at the end.
• You passed x as a parameter in the line Opponent character1 = new Opponent(y);, even though you were trying to define x with the parameter. Give it a different value.
One note: why would you define an instance of the class in the class? Instead of using this:
Opponent character1 = new Opponent(y);
System.out.println(character1.x + "");
You could just write this:
System.out.println(Opponent.x + "");
However, you could create character1 if you were accessing class Opponent from a different class.
I honestly don't know what your question is, but try running this:
public class Opponent {
public int x;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
Opponent character1 = new Opponent(5);
System.out.println(character1.x); // this will output: 5
}
}
A few problems with your question:
you are trying to initialize a static variable thinking its an instance variable?
x is not initialized in main()
value is not defined as a field in Opponent
maybe something like this. i leave the random number generation up to you:
public class Opponent
{
private int score;
public Opponent()
{
// you probbaly want to override this with
// a random number generator
this.score = 0;
}
public Opponent(int value)
{
this.score = value;
}
public int getScore()
{
return this.score;
}
public void setScore(int score)
{
this.score = score;
}
public static void main(String[] args)
{
Opponent character1 = new Opponent();
Opponent character2 = new Opponent(5);
int result = character1.getScore() - character2.getScore();
System.out.println(result);
}
}

Categories

Resources