I created a class for a bingo game. I get an error saying "'class' expected". How could I return the values in the array to the main starter?
Any other comments would also be helpful.
Thank you.
import java.util.Random;
public class Card
{
Random generator = new Random();
private final int BOARDMAX = 4;
private final int NUMMAX = 59;
int i, j, m, n;
private int [][] ArrayBoard = new int[BOARDMAX][BOARDMAX];
String [][] StrArrayBoard = new String [BOARDMAX][BOARDMAX];
public void RandomNumGenerator()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
ArrayBoard[i][j] = generator.nextInt (NUMMAX+1);
}
}
}
public String ShowBoard()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
m=i;
n=j;
if (j != BOARDMAX)
StrArrayBoard[m][n] = ArrayBoard[m][n] + " ";
else
StrArrayBoard[m][n] = ArrayBoard[m][n] + " \n";
}
}
return StrArrayBoard[i][j];
}
public void ShowMark()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
if (CardCheck [i][j] == 1)
StrArrayBoard[i][j] = ArrayBoard[i][j] + "* ";
else
StrArrayBoard[i][j] = ArrayBoard[i][j] + " ";
if (j == BOARDMAX)
ArrayBoard[i][j] = ArrayBoard[i][j] + "\n";
}
}
}
public String toString()
{
return ArrayBoard[][];
}
}
With toString() you need to return a String object but actually you try to return an int[][]. The same is true for ShowBoard, you try to return an array of Stringarrays which is not a compatible type.
Here's the fix:
public String ShowBoard() {
// your code to populate StrArrayBoard
StringBuilder boardBuilder = new StringBuilder();
for (String[] row:StrArrayBoard)
for (String cell:row)
sb.append(cell);
return boardBuilder.toString();
}
public String toString() {
return ShowBoard();
}
I suggest to refactor the code and rename methods and fields:
ShowBoard() --> getBoardAsString()
ArrayBoard --> arrayBoard
StrArrayBoard --> strArrayBoard
And there's no need to declare StrArrayBoard as a field (class member) just because you only need it inside the ShowBoard method. Declare it there as a local variable.
Adding to the bugs others have pointed:
You have if (CardCheck [i][j] == 1), but the array CardCheck is not declared anywhere.
You have ArrayBoard[i][j] = ArrayBoard[i][j] + "\n"; but ArrayBoard is an int array, you cannot add a string "\n" to it's member.
The compiler will complain because of the error on your code:
public String toString()
{
return ArrayBoard[][];
}
It can't convert int[][] (which is your ArrayBoard) to String. My suggestion is that you populate all values stored in StrArrayBoard in a StringBuffer and return the StringBuffer.toString() in the toString() method.
The toString() method requires a String.
Hope this helps.
public String toString()
{
return ArrayBoard[][];
}
This method expects to return a String but you are returning a 2D Integer array, what you need is a String. the toString() method returns a string representation of the object, so in this case, what you can do is to use a StringBuilder to build the string representation of the array and then, use the .toString() of the StringBuilder to return the string representing the 2D Array.
Also, as noted by Alois Cochard, you variable naming does not follow convention. Variable names in Java use a camel case notation.
I for one don't really understand your question but I've got a couple of comments.
The class variables i and j should be local variables in each method.
Your naming convention is nonstandard, seems like a more C# convention. Start variable and method names with a lower case.
CardCheck isn't defined anywhere. I presume it is meant to indicate if a number on a square has been checked, in which case it should be a boolean and not an int.
toString doesnt return a string. You can use Arrays.toString to help you.
Similarily, ShowBoard just returns one element of an array, you probably wanted to show the entire board there.
For your toString and ShowBoard methods you probably want to use a StringBuilder to build up the string representation.
StringBuilder builder = new StringBuilder();
for (int i=0; i<BOARDMAX; i++) {
for (int j=0; j<BOARDMAX; j++) {
builder.append(StrArrayBoard[i][j]);
}
builder.append('\n');
}
return builder.toString();
Here's a version of your class that compiles (and I changed some field names and modifiers to adhere to standard conventions). Try this:
public class Card{
private final Random generator = new Random();
private static final int BOARDMAX = 4;
private static final int NUMMAX = 59;
int i, j, m, n;
private final int[][] arrayBoard = new int[BOARDMAX][BOARDMAX];
private final String[][] strArrayBoard = new String[BOARDMAX][BOARDMAX];
// do something here please
private int[][] CardCheck;
public void RandomNumGenerator(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
arrayBoard[i][j] = generator.nextInt(NUMMAX + 1);
}
}
}
public String ShowBoard(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
m = i;
n = j;
if(j != BOARDMAX){
strArrayBoard[m][n] = arrayBoard[m][n] + " ";
} else{
strArrayBoard[m][n] = arrayBoard[m][n] + " \n";
}
}
}
return strArrayBoard[i][j];
}
public void ShowMark(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
if(CardCheck[i][j] == 1){
strArrayBoard[i][j] = arrayBoard[i][j] + "* ";
} else{
strArrayBoard[i][j] = arrayBoard[i][j] + " ";
}
if(j == BOARDMAX){
// this is probably what you mean:
strArrayBoard[i][j] = arrayBoard[i][j] + "\n";
}
}
}
}
#Override
public String toString(){
// this is probably what you mean:
return Arrays.deepToString(strArrayBoard);
}
}
Related
I have the following code and would like to get the two functions mentioned in the title running. They are appearing in color red, which means they are not being recognized. I've imported the library 'import java.lang.*' but it is still not working.
import java.lang.*;
public class Practice {
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int first, second, i, j,value, value2, value3, value4, value5, value6;
first = firstWord.length;
second = secondWord.length;
value = 0;
value2 = 0;
char[] charArray = firstWord.toCharArray();
char[] charArray2 = secondWord.toCharArray();
char[] charArray3 = targetWord.toCharArray();
for(i = 0; i < first; i++)
{
value = getNumericValue(charArray[i]);
value2 = value2 + value;
}
for(j = 0; j < second; j++)
{
value3 = getNumericValue(charArray2[i]);
value4 = value4 + value3;
}
for(j = 0; j < second; j++)
{
value5 = getNumericValue(charArray2[i]);
value6 = value6 + value5;
}
if( (value2 + value4) == value6)
return true;
return false;
}
public static void main(String[] args){
Practice example = new Practice();
String firstWord = ("aaa");
String secondWord = ("a");
String targetWord = ("aab")
boolean value;;
value = example.isSumEqual(firstWord, secondWord, targetWord);
System.out.println(value);
}
}
I see that you called this class Practice, hence I took your code and improved it by removing duplicated code.
public class Practice {
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int valueOfFirstWord = getValueOfWord(firstWord),
valueOfSecondWord = getValueOfWord(secondWord),
valueOfThirdWord = getValueOfWord(targetWord);
return valueOfFirstWord + valueOfSecondWord == valueOfThirdWord;
}
private int getValueOfWord(String word) {
int value = 0;
for(int i = 0; i < word.length(); i++) {
value += Character.getNumericValue(word.charAt(i));
}
return value;
}
public static void main(String[] args){
Practice example = new Practice();
String firstWord = ("aaa");
String secondWord = ("a");
String targetWord = ("aab");
boolean value = example.isSumEqual(firstWord, secondWord, targetWord);
System.out.println(value);
}
}
Others have already posted an answer for you, therefore I'll only display this version for you as a reference.
No need to import java.lang.*, it's always imported in each java file by default.
String doesn't have such field as length, but has a method length(). So, you should write str.length().
To call getNumericValue() you should write Character.getNumericValue() or add static import: import static java.lang.Character.getNumericValue
As said in the comments, the method length() needs to be called with parentheses like this:
firstWood.length()
The other method getNumericValue(char ch) is associated with the Character Class, so you use the method like this:
value = Character.getNumericValue(charArray[i]);
i hope someone can help me, i have the following problem.
I have a variable that looks like this:
var a = "01VENT000KRV010WFEVVV055";
I would like to either:
have the last 3 figures of the variable (e.g. 055) as an int
or remove ALL non-figures out of the variable (e.g. 01000010055) as an int
My idea was that:
int sub = Integer.parseInt(a.substring(a.length-3));
or:
int sub = Integer.parseInt(a.replaceAll("[\\D]", ""));
That didnt work, so i would really appreciate if someone could help me here
Thanks
Note all methods can potentially return an empty string.
public static void main(String[] args) {
// TODO code application logic here
String a = "01VENT000KRV010WFEVVV055";
System.out.println(removeChars(a));
System.out.println(removeDigits(a));
System.out.println(getLastThreeChars(a));
}
//This method removes Characters from a string and returns a String of numbers
static String removeChars(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isDigit(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This method removes Digits from a string and returns only characters
static String removeDigits(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isAlphabetic(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This methods prints the last 3 char of a string
static String getLastThreeChars(String t)
{
StringBuilder tempString = new StringBuilder();
for(int i = t.length() - 1; i > t.length() - 1 - 3; i--)
{
tempString.append(t.charAt(i));
}
return tempString.reverse().toString();
}
Printing out a 2d character array is not difficult, but the way I need to do it seems to be.
My current goal is initialize a 2d character array, such that every cell contains '-'. This must be done within the constructor method. Below is what I have thus far.
public class GameOfLife {
public final int MAX_SIZE = 12;
// instance variables
private char [][] current = new char[MAX_SIZE][MAX_SIZE];
private char [][] next = new char[MAX_SIZE][MAX_SIZE];
Scanner keyboard = new Scanner(System.in);
/**
* Constructor for objects of class GameOfLife.
* Initializes the current array to '-'.
*/
public void GameOfLife() {
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
current [i][j] = '-';
}
}
#Override public String toString() {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
sb.append(current[i][j]);
sb.append(" ");
}
sb.append("\n"); // add new line
}
return sb.toString(); // convert to String and return
}
}`
I know how to properly print it if it were just to be printed within this method; however, I must use the "GameOfLife" constructor in the following way. This next code is in the driver class, which is called "gameoflifedriver".
// Create a GameOfLife object
GameOfLife lifeGame = new GameOfLife();
System.out.print(lifeGame);
The problem that I am having is that the lifeGame will not print, and an odd error message occurs - GameOfLife#5d3892b3. I know there are ways to print it, but I cannot change any of the code in the driver class - so all of the edits must be in the GameOfLife code. Any thoughts?
You can override the toString() method. Also you could use a StringBuilder:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
sb.append(current[i][j]);
sb.append(" ");
}
sb.append("\n"); // add new line
}
return sb.toString(); // convert to String and return
}
Then you can print this representation with:
GameOfLife lifeGame = new GameOfLife();
System.out.print(lifeGame);
Note: Constructors don't have a return type, so you shouldn't declare it with return type void:
public GameOfLife() {/* Constructor body */}
The Class GameOfLife constructor should not have void return type (java rule).
And the toString() method is good to implement.
From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Java code with tests - infinite loop?
Here is my code that I want to get the relationship between people, however, when I run unit test, the test ran forever and couldn't get the result, and my cpu using was high.
Here is my code. Could someone see what's wrong with it?
the string relations are multiple line inputs of string with a format "A , B" +\n" +
"C , D" where A is the parent of B and C is the parent of D.
this is the default constructor for the code and is the input format of string, we don't need to check if the format is correct
public SeeRelations(String relations){
this.relations = relations;
}
//helper function to get each line of the string
private ArrayList<String> lineRelations(){
int i;
ArrayList<String> lineRelations = new ArrayList<String>();
String[] lines = relations.split("\n");
for(i = 0; i < lines.length; i++){
lineRelations.add(lines[i]);
}
return lineRelations;
}
//helper function to put each of the relationship in arraylists
private ArrayList<ArrayList<String>> allRelations(){
int i;
ArrayList<ArrayList<String>> allRelations = new ArrayList<ArrayList<String>>();
ArrayList<String> lineRelations = lineRelations();
for(i = 0; i < lineRelations.size(); i++){
ArrayList<String> eachLine = new ArrayList<String>(Arrays.asList(lineRelations.get(i).split("\\s*,\\s*")));
allRelations.add(eachLine);
}
return allRelations;
}
this is the method to check if the input name is existent
//helper function to see if the name exist for seeRelations()
private boolean hasThisName(String name){
ArrayList<ArrayList<String>> allRelations = allRelations();
int i;
int j;
for(i = 0; i < allRelations.size(); i++){
for(j = 0; j < allRelations.get(i).size(); j++){
if(name.equals(allRelations.get(i).get(j))){
return true;
}
}
}
return false;
}
this is the function to get the generation number between two people
//helper function to get Generation number of seeRelations()
private int getGenerationNum(String person, String ancestor){
ArrayList<ArrayList<String>> allRelations = allRelations();
String name;
int i;
int j;
int generationNum = 0;
for(i = 0, j = 0, name = ancestor; i < allRelations.size(); i++){
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
else if(ancestor.equals(allRelations.get(i).get(0)) && person.equals(allRelations.get(i).get(1))){
generationNum++;
j = 1;
break;
}
}
if(j == 0){
return 0;
}
else{
return generationNum;
}
}
this is the method to get multiple of "great" for the final output
private String great(int num){
int i;
String great = "";
for(i = 0; i < num; i++){
great += "great";
}
return great;
}
this is my final method to check the relationship between two people
public String seeRelations(String person, String ancestor){
int generationNum = getGenerationNum(person, ancestor);
String great = great(generationNum - 2);
if(!(hasThisName(person) && hasThisName(ancestor))){
return null;
}
else{
if(generationNum == 0){
return null;
}
else if(generationNum == 1){
return ancestor + " is the parent of " + person;
}
else if(generationNum == 2){
return ancestor + " is the grandparent of " + person;
}
else{
return ancestor + " is the" + " " + great +"grandparent of " + person;
}
}
}
This piece of code looks suspicious to me. It is inside a loop that depends for termination on incrementing i, but conditionally resets i back to zero. What guarantees i will ever get past 1?
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
In general, I suggest simplifying your code until it works, then adding gradually so that you only have to debug a small piece of code at a time.