So i'm trying to call a method displayBoard in java that displays the boardgame once the user enters in a number initially in the main method. I'm unable to call this method. Does anyone see where i'm going wrong or how do i fix this? Thanks.
public static void displayBoard(int [] board, boolean showItem)
{
System.out.println();
System.out.print("_");
for (int val : board){
switch(codes){
case 2:
System.out.print("x");
break;
case 3:
System.out.print(" ");
break;
case 4:
System.out.print(showItem ? "Y" : " ");
break;
}
System.out.print("_");
} //for
System.out.println();
System.out.println();
}//display
public static void main (String [] args)
{
int guess = 0;
int userInput = promptForInt("Length Of board");
int [] numbers = new int[userInput];
int randomlocs = new Random().nextInt(userInput);
int val;
int display = displayBoard(board [], boolean showItem) // doesnt work?
boolean showItem = false;
while(! showItem)
{
val = promptForInt("Try Again!");
if(guess == randomlocation)
{
System.out.println("Found it!");
showItem = true;
}
else if(guess != randomlocs)
System.out.print(val);
}
}
Problem
You must pass values to the method call. Right now, you are passing declarations to the method, which isn't proper Java syntax
How To Fix
First, declare your showItem boolean before you call the method so you have a boolean to pass to the method. It should look like this:
boolean showItem = false;
int display = displayBoard(numbers, showItem)
This will pass the vakues stored in your numbers and showItem variables. We know the values stored in these specific variables (numbers and showItem) should be passed in due to the method's parameter names.
The statements leading up to that method call should look like this:
int userInput = promptForInt("Length Of board");
int [] numbers = new int[userInput];
boolean showItem = false;
int display = displayBoard(board [], boolean showItem);
int randomlocs = new Random().nextInt(userInput); //since this isn't used before the method call, it should be declared below it
int guess = 0; //same with this
int val; //and this
Related
I bought Head First Java book, and i am trying to do the exercise sink a startup.
After a while the book introduce ArrayList, and show how to use it in the class and its' method.
Problem is once i change everything with arraylist, the MAIN doesn't work, becasue at start i used simple INT, in the array location, now it need array.
How can i change the values of INT into a type that i can put inside the array ?
thx for help, and here the code.
the class with the method:
private ArrayList<String> locationCells;
private int numOfHits = 0;
public void setLocationCells(ArrayList<String> locationCells)
{
this.locationCells = locationCells;
}
public String checkYourself(String guess) {
// creazione stringa miss
String result = "miss";
int index = locationCells.indexOf(guess);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
numOfHits ++;
}else
result = "hit";
System.out.println(result);
return result;
}
and here the MAIN:
public static void main(String[] args) {
java.util.Random randomGenerator = new java.util.Random();
Scanner scan = new Scanner(System.in);
StartUpCorretta dot = new StartUpCorretta();
int manyGuesses = 0;
boolean isAlive = true;
int randomNumbers = randomGenerator.nextInt(5) +1;
int randomNumb = (int) (Math.random() * 5);
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
dot.setLocationCells(location);
while(isAlive) {
System.out.println("enter a number");
int guess = scan.nextInt();
String result = dot.checkYourself(guess);
manyGuesses ++ ;
if (result.equals("kill")) {
isAlive = false;
System.out.println("you took" + " " + manyGuesses + " " + "guesses");
}
}
}
Seems, you are taking your input from console as int from this statement
int guess = scan.nextInt();
So, my answer is based on your input data type.
Please, changed your arraylist generic type String to Integer
And Secondly, this is not how you can initialized the arraylist
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
Correct way to create collection using new operator like this
ArrayList<Integer> location = new ArrayList<>();
and correct way to add element into arraylist like this
location.add(randomNumbers);
location.add(randomNumbers+1);
location.add(randomNumbers+2);
Hope, it will work for you.
I am trying to figure out why my program doesn't seem to be stepping into one of my methods: assignKennel(). Instead, it keeps asking for more input, even though theres more to do in the while loop. Any advice will be much appreciated. I'm not sure what to include, so here is all I have.
package finalbarking;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Finalbarking {
//global int numberOfDogs, numberOfKennels;
static int numberOfDogs, numberOfKennels=8;
//int dogID
static int [] dogIDs= new int [15];
//add provided ID's
//String dogNames
static String [] dogNames= new String [15];
//add provided dogs to array
//int dogWeights
static int [] dogWeights= new int [15];
//add provided weights to array
//at start, this is empty.
//array size = 8 elements myArray = new int[7]
//int KennelNumber
static int [] kennelNumbers= new int [8];
//String kennelWeight(SMALL / MEDIUM / LARGE)
static String [] kennelWeight= new String [3];
//int dogInKennelID
static int [] dogInKennelID= new int [8];
static int inputDogID=0;
public static void main(String[] args) throws InterruptedException {
//vars
//Scanner
Scanner response= new Scanner(System.in);
//int inputDogID
dogIDs[0]=1001;
dogIDs[1]=1003;
dogIDs[2]=1007;
dogIDs[3]=1008;
dogIDs[4]=1012;
dogIDs[5]=1034;
dogIDs[6]=1038;
dogIDs[7]=1087;
dogIDs[8]=1088;
dogIDs[9]=1120;
dogIDs[10]=1129;
dogIDs[11]=1145;
dogIDs[12]=1200;
dogIDs[13]=1211;
dogIDs[14]=1222;
dogNames[0]= "Bowser";
dogNames[1]= "Ginger";
dogNames[2]= "Molly";
dogNames[3]= "Murphy";
dogNames[4]= "Roxy";
dogNames[5]= "Samantha";
dogNames[6]= "Duke";
dogNames[7]= "Pookie";
dogNames[8]= "Abby";
dogNames[9]= "Barney";
dogNames[10]= "Autumn";
dogNames[11]= "Hershey";
dogNames[12]= "King";
dogNames[13]= "Bosco";
dogNames[14]= "Daisy";
dogWeights[0]=130;
dogWeights[1]=80;
dogWeights[2]=45;
dogWeights[3]=18;
dogWeights[4]=70;
dogWeights[5]=12;
dogWeights[6]=90;
dogWeights[7]=16;
dogWeights[8]=35;
dogWeights[9]=65;
dogWeights[10]=20;
dogWeights[11]=100;
dogWeights[12]=110;
dogWeights[13]=70;
dogWeights[14]=55;
kennelWeight[0] = "SMALL";
kennelWeight[1] = "MEDIUM";
kennelWeight[2]= "LARGE";
//reset at end
//Greeting for employee
System.out.println("Hello Barking Lot Employee!");
//begin loop
while(inputDogID!=9999){
//try
try{
//prompt for dog id, 9999 as sentinel value
System.out.println("Please enter the dog's ID number, or '9999' to quit)");
//capture
inputDogID= response.nextInt();
//end try start catch exception
}catch(InputMismatchException error){
//Invalid
System.err.println("You've entered an invalid Dog ID. Try again(Please refer to our Dog Client List, they are all 4 digits long).");
//pause program
Thread.sleep(10);
//reset scanner
response = new Scanner(System.in);
}//end catch
int foundDogID = 0;
for(int count=0; count<15; count++)
{
if(dogIDs[count] == inputDogID){
foundDogID = count;
}//end if
}//end for
currentClients(dogIDs,dogNames,dogWeights,inputDogID);
//assignKennel()
assignKennel(foundDogID);
//displayKennel();
displayKennel();
}//endwhile
}//end main
//User Defined Methods
//CurrentClients- Identifies dog based on list of current clients
public static void currentClients(int[]dogIDs,String[]dogNames,int[]dogWeights,int inputDogID){
//Takes 3 arrays(ID, NAME, WEIGHT)
//Takes inputDogID
//Iterate the array and check if inputDogID == ID[count]
//for(int count = 0; count < numberOfDogs; count++)
for(int count = 0; count <= numberOfDogs; count ++){
//if(inputDogID == ID) then return NAME + WEIGHT;
if(inputDogID==dogIDs[count]){
System.out.println("Dog Name : "+dogNames[count]+"\tDog Weight: "+ dogWeights[count]);
}//end if
//else then return 0 and display an error
else
System.out.println("Did not find a dog matching this ID Number.");
}//end for
}//endCurrentClients
//assignKennel-assigns dogs to kennels
public static void assignKennel(int dogIDs){
//takes 1 int dogID
//Iterate the array and check:
//var
boolean didDogGetKennel=false;
for(int count = 0; count < numberOfKennels; count++){
//if(getDogWeightClass(dogWeights[dogID]).equals(kennelWeight[count]))
String weightClass = getDogWeightClass(dogWeights[dogIDs]);
for(int counter = 0; counter < 3; counter++)
{
if(weightClass.equals(kennelWeight[counter]))
{
if(dogInKennelID[count] == 0){
//then EMPTY, assign
didDogGetKennel=true;
dogInKennelID[count]=dogIDs;
}//end if
}
}
}//end for loop
//if didDogGetKennel=false display message: "I'm sorry all ken
if(didDogGetKennel==false)
System.out.println("I'm sorry, all of our kennels for that weight limit are filled.");
}//end assignKennel
//displayKennel- displays the eight kennel numbers &the dog assigned to each
public static void displayKennel(){
// print if all kennels are filled
if(areKennelsFull()){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end if
//else if print if sentinel value is enter
else if(inputDogID==9999){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end else if
}//end displayKennel
//getDogWeightClass()
public static String getDogWeightClass(int dogWeight){
//take int dog weight
//if dog weight < 50, then SMALL
if(dogWeight<50)
return "SMALL";
//else if dog weight >50 &&<100 then MEDIUM
else if(dogWeight>50 &&dogWeight <100)
return "MEDIUM";
//else then LARGE
else
return "LARGE";
//return String S/M/L
}//end getDogWeightClass
//getDogName()
public static String getDogName(int dogInKennelID){
//take dogInKennelID
return dogNames[dogInKennelID];
}//end getDogName
//areKennelsFull()
public static Boolean areKennelsFull(){
for(int count =0; count<=8; count ++){
if (dogInKennelID[count] ==0)
return false;
//return boolean false
//else return boolean true
else
return true;
}//end for
return false;
}//end areKennelsFull
}//end class
It actually does run assignKennel(). If you put a System.out.println() statement in there to verify that that method runs, you'll see that it does. The problem isn't with that method; every method is running as it should.
Your problem is in displayKennel(). It isn't doing anything. areKennelsFull() evaluates to false, as does inputDogID==9999 (assuming some other id was typed in). I'm guessing areKennelsFull() is supposed to evaluate to true after a valid ID has been entered, so the root cause of this problem is most likely either in areKennelsFull() or perhaps in assignKennels() incorrectly assigning a value somewhere in dogInKennelID.
It does enter that routine, but one problem I see is that you are exceeding the array index. You have the condition "count<=8" in 3 for statements which should read "count<8" (remove the "="). When it tries to use index 8, it bombs, and so the program cannot finish properly. The array is indexed from 0 to 7, so 8 is invalid.
I am currently getting error code
TOOLS.java:48: error: incompatible types: ToolItem[] cannot be converted to int[]
when running this program that extends from a .class.
The issue is with the line
int indEX = SearchArray(toolArray, srchnum);
I'm not sure what the issue is. The only thing I can think of is toolArray contains information about tools from the ToolItem class, which has Strings as well as integers and doubles, for storing tool information like name/ID/quantity etc. I'm not sure where I went wrong. I can post the .class if needed
public class TOOLS extends ToolItem
{
// Private members
private int numberOfItems;
private ToolItem[] toolArray = new ToolItem[10];
Scanner keyboard = new Scanner(System.in);
public TOOLS()
{
int numberOfItems = 0;
for (int i=0; i<10; i++)
toolArray[i] = new ToolItem();
}
// search method
public static int SearchArray(int[] toolArray, int srchnum)
{
int i=0;
while (i < toolArray.length)
{
if (toolArray[i] == srchnum)
return i;
else
i++;
}
return -1;
}
// calling search method
public void main(String[] args)
{
int srchnum;
System.out.println("Enter a toolID to search: ");
srchnum = keyboard.nextInt();
int indEX = SearchArray(toolArray, srchnum);
if (indEX == -1)
System.out.println(" " + srchnum + "No ID match");
else
System.out.println(" " + srchnum + "was found at " + indEX);
}
}
Well you declared private ToolItem[] toolArray = new ToolItem[10]; but you're calling a function that asks for an int array:
public static int SearchArray(int[] toolArray, int srchnum)
Based on your code it would seem that you're trying to search by index in the array? You could change the parameter of the function you're calling and then use the getIndex() method on the specified array to compare the index with the srchnum.
//Changed first parameter type
public static int SearchArray(ToolItem[] toolArray, int srchnum)
{
int i=0;
while (i < toolArray.length)
{
//Get the index of the toolArray at position 'i'
if (toolArray[i].getIndex() == srchnum)
return i;
else
i++;
}
return -1;
}
My project is finally complete, but my only problem is that my teacher does not accept "breaks" in our code. Can someone help me resolve this issue, I have been working on it for days and I just can't seem to get the program to work without using them. The breaks are located in my DropYellowDisk and DropRedDisk methods. Other then that issue, my connect four program is flawless.
private static void DropYellowDisk(String[][] grid) {
int number = 0;
Scanner keyboard = new Scanner (System.in);
System.out.println("Drop a yellow disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
for (int i=6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "Y";
break;
}}
}
private static void DropRedDisk(String[][] grid) {
Scanner keyboard = new Scanner (System.in);
System.out.print("Drop a red disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
for (int i =6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "R";
break;
}
}}
my teacher does not accept "breaks"
From a programming standpoint, that's just plain silly (although I'm sure it has merit from an instructional one).
But there's an easy workaround in this particular case because the loops your breaking from are all at the end of their respective methods. As such, you can replace them with return statements. i.e:
private static void DropYellowDisk(String[][] grid) {
for (int i=6;i>=0;i--)
{
if (grid[i][c] == " ")
{
grid[i][c] = "Y";
return; //break
}}
}
boolean flag = false;
for (int i=6;i>=0 && !flag;i--) {
if (grid[i][c] == " ") {
grid[i][c] = "Y";
flag = true;
}
}
You can use boolean flag instead of break with while loop. Also you should compare strings by the equals method.
private static void DropYellowDisk(String[][] grid) {
int number = 0; boolean flag=true;
Scanner keyboard = new Scanner (System.in);
System.out.println("Drop a yellow disk at column (1–7): ");
int c = 2*keyboard.nextInt()+1;
int i=6;
while(i>=0&& flag)
{
if(grid[i][c].equals(" "))
{
grid[i][c]="Y";
flag=false;
}
i--;
}
}
This program works fine if i enter the correct value (int value). However, when I enter in a character or any other wrong value it displays the wrong input message and calls the main method again. The only problem is after calling the main method and inputting the correct input it prints out extra data why is that?
import javax.swing.JOptionPane;
public class TestPolyVal {
public static void main(String[] args){
int xValue = 0;
String value = JOptionPane.showInputDialog(null, "What is the value of X");
try{
xValue = Integer.parseInt(value);}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
}
int[] intArray = new int[20] ;
for (int i = 0; i < 20; i ++){
intArray[i] = 2;}
System.out.println(calculateBruteForce(intArray,xValue));
System.out.println("0");
System.out.println(calculateHorner(intArray,xValue));}
static int calculateBruteForce(int[] a, int b){
int sum = 0 ;
for (int i = 0; i < 20; i ++){
sum +=a[i]*powerCalc(b,i);}
return sum;}
static int powerCalc(int c, int d){
int powerValue = c;
if (d==0){
powerValue = 1;}
else if (d==1){
powerValue = c;}
else if (d>1){
for (int i = 1; i<d;i++){
powerValue = powerValue*c;}}
return powerValue;}
static int calculateHorner(int[] e, int f){
int acc = e[e.length-1];
for(int i = e.length-2; i >= 0; i--){
acc = (acc * f)+ e[i];}
return acc;}
}
You are getting extra printouts because the first main execution will continue after the second main invocation is done.
This can be fixed by adding a return; after the new call to main:
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
return;
}
The approach of calling main() from within main() is not a great approach in this case. I, as an adversarial user, could just type 'a' in the dialog over and over again. Eventually this would cause a Stack Overflow Error and your program would crash.
I would suggest using a loop.
while(true) {
try{
xValue = Integer.parseInt(value);
break;
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
}
}
This way your program would just loop forever or until the user enters correct input instead of crashing. Unless you're implementing a recursive algorithm, I can't think of any reason for a method to invoke itself.