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--;
}
}
Related
I'm trying to get better at java by making a Sudoku puzzle, however I'm running in to some issues. As it currently stands, if I put any "illegal" input in the Sudoku, it just continues, but I'm trying to make the script ask for a value again if it is "illegal". As seen below in the code, it is when my public boolean "moves" is false I'm trying to start the while loop once again.
public static void main(String[] args) throws Exception {
Sudoku s = new Sudoku("C:\\Users\\caspe\\Downloads\\Sudoku001.sdk");
s.printBoard();
s.errorCheck();
s.getNum();
while(getNum() > 0) {
System.out.println("Next move, please (row , column , value )");
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt() ;
int value = scanner.nextInt();
if (s.moves(row, column, value) == false); {
//Try again
}
s.printBoard();
}
}
I still can't figure out an solution after several different attempts, so help is very much appreciated!
This is my getNum method for further understanding:
public static int getNum() {
int getNumb = 0;
for(int j = 0; j < list.size(); j++) {
for (int i=0; i < list.get(j).length(); i++) {
if(list.get(i).charAt(j) == '.') {
getNumb++;
}
}
}
return getNumb;
}
The way you have written your code it is going to print the Sudoku board whether s.move is true or false. The way you would fix that is by add in an else statement to your if statement.
For example:
if(s.moves(row, column, value) == false){
//print error message
}else {
s.printBoard();
}
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
I'm trying to send a variable out of a 'for' loop, and save it to a string in another class, but I just end up with the latest input when doing a system print in the last class. Now I suspect this is because of;
ProcessInput c = new ProcessInput();
But I cannot for the life of me understand how I work around that particular problem.
I realize this could be avoided if I appended latest input to a string, and sendt the string after the loop finished. Alas my assignment is not so. Also I'm quite new at this, so be gentle.
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = userInput.next();
c.paste(feedback);
}
}
}
public class ProcessInput {
public void paste(String feedback) {
String line = "";
line += feedback + " ";
System.out.println(line);
}
}
The line is in the local scope of the method and therefore, it is reset every time the method is called. You need to make it an instance variable, so that for every instance created, it preserves the value for that instance.
public class ProcessInput {
String line = ""; // outside the paste method, in the class
public void paste(String feedback) {
line += feedback;
System.out.println(line);
}
}
The concept that you must understand is java is pass by value and not reference, So you are only passing the new input entered every time to the method "paste".
Simple solution
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = feedback+userInput.next();
c.paste(feedback);
}
}
public class ProcessInput {
public void paste(String feedback) {
System.out.println(feedback);
}
}
It is more important you understand the underlying concept of passing values between methods in java.
**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}
(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.
Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.
Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).
Classic java starter error. while check stetement should be
While(retry == true)
I made a java login screen for a console application, but I need it to allow the user to input ther wrong PIN only 3 times. After the user has entered the PIN more than 3 times, the system should exit.
However, the loop which I used for the else part of the if condition does not seem to be making any changes to the program. (program wont execute the else part even once). Does anybody know what I am doing wrong?
if (userPIN.equals(a[0]))
{
System.out.println("You have login!");
valid=true;
String b=a[2];
Login.c=Double.parseDouble(b);
System.out.println(c);
obj.balance = Login.c;
obj.MainMenu();
System.exit(0);
}
else if(userPIN != a[0])
{
int count=0;
for(int i=0;i<count;i++)
{
System.out.println("Invalid PIN!");
check();
}
}
int count=0;
for(int i=0;i<count;i++)
The for loop's condition is initially false, hence it will never execute its body.
You have many problems in your code :
in the first if your using :
userPIN.equals(a[0])
but in the else you're using :
userPIN != a[0]
Your for loop cannot run correctly :
int count=0;
for(int i=0;i<count;i++)
Here is the correct implementation using Object-Orientation :
import java.util.Scanner;
public class PinChecker {
// Immutable Class
private static final class Pin {
private String _pin;
Pin(String pin) {
this._pin = pin;
}
public String toString() {
return _pin;
}
public boolean equals(Pin pin) {
if(pin.toString().equals(_pin)) {
return(true);
} else {
return(false);
}
}
}
public static final int NB_OF_TRIES = 3;
public static void main(String[] args) {
System.out.println("Enter your PIN :");
Pin userPin = new Pin("FOO");
Scanner console = new Scanner(System.in);
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
Pin keyedPin = new Pin(console.nextLine());
i++;
if(userPin.equals(keyedPin)) {
pinMatch = true;
} else {
System.out.println("Invalid PIN!");
}
}
if(pinMatch) {
System.out.println("OK, nb of tries :" + i);
} else {
System.out.println("KO, nb of tries :" + i);
}
}
}
You can store the keyedPin object if you need to.
in the else part try !(userPIN.equals(a[0]))
Your else part is not checking the contents.