Going back and forth with methods in Java - java

I built a tic tac toe game using java but I just have one issue. I want my code to bounce back and forth from the validPlayerOneInput and validPlayerTwoInput methods. As you can see in my main, I'm calling both methods procedurally which be incorrect as it just stops after the method is called. I want this to keep running until a winner is determined.
How do I do so?
import java.util.*;
public class tictactoe {
private static char board[][] = {{1,2,3}, {4,5,6}, {7,8,9}};
char p1Sym, p2Sym;
public tictactoe() {
p1Sym ='X';
p2Sym = 'O';
boardFill();
}
void boardFill() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j]);
System.out.print(" | ");
}
System.out.println();
}
}
void validInputPlayerOne() {
boolean isSet = true;
int player1Input, player1CorrectedInput;
System.out.println("Player 1, enter a number between 1-9: ");
Scanner player1 = new Scanner(System.in);
player1Input = player1.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player1Input < 1 || player1Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player1CorrectedInput = correctedInput.nextInt();
player1Input = player1CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player1Input) {
// set new value
board[i][j] = p1Sym;
// set
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
void validInputPlayerTwo() {
boolean isSet = true;
int player2Input, player2CorrectedInput;
System.out.println("Player 2, enter a number between 1-9: ");
Scanner player2 = new Scanner(System.in);
player2Input = player2.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player2Input < 1 || player2Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player2CorrectedInput = correctedInput.nextInt();
player2Input = player2CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player2Input){
board[i][j] = p2Sym;
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
public static void main(String[] args) {
tictactoe t = new tictactoe();
t.validInputPlayerOne();
t.boardFill();
t.validInputPlayerTwo();
t.boardFill();
}
}

You could do something like:
int turn = 0;
while (t.noWinner()) {
if (turn % 2 == 0) t.validInputPlayerOne();
else t.validInputPlayerTwo();
t.boardFill();
turn += 1;
}
Of course, now you have to actually write the noWinner function.

Answering your question directly, you could have a boolean that toggles on each move:
boolean firstPlayer = true;
while (t.gameIsNotFinished()) {
if (firstPlayer)
t.validInputPlayerOne();
else
t.validInputPlayerTwo();
firstPlayer = !firstPlayer;
}
However you have a lot of other issues with your code that you need to address. For example if a player enters an invalid value then it goes to the next player rather than asking for them to reenter the value.
You should also try to have a single validInputPlayer method that works for both players with the firstPlayer variable passed in. At the moment you have a lot of repeated code in those methods.

Related

What do I need here in my code to check if an element in an array is the same with the previous

I need to make a program to compare if an element in an array has the same value, if there is an element in the array that are the same, it prints "Yes", otherwise "No".
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class DistinctNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
for (int i = 0; i < arrayA.length; i++) {
for (int j = i + 1; j < arrayA.length; j++) {
arrayA[j] = scanner.nextInt();
if (arrayA[0] == arrayA[i++]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
}
[Edited] (see below)
Do you mean something like this?
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
for (int i = 0; i < sizeN; i++) {
arrayA[i] = scanner.nextInt();
for (int j = 0; j < i; j++) {
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
Can you please give us an expected input with an expected output?
You want a simple Yes or No as output or a series of Yes or Nos as an output?
[Edit]
If you are trying to check whether there are 2 or more numbers in the array with the same value this might work for you (however it's not optimal):
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
boolean found = false;
for (int i = 0; !found && i < sizeN; i++) {
arrayA[i] = scanner.nextInt();
for (int j = 0; !found && j < i; j++) {
if (arrayA[i] == arrayA[j]) {
found = true;
}
}
}
if (found) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
I think you wants to do :
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
if any elements of array same, it will be 'Yes'

Matching array values with variables

In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}

Code detects string as having duplicate letters, even when it does not

I wrote a program to check whether a word does not have any duplicate letters. There are two problems I am having:
1 - I wrote this in object oriented code and I am having an issue calling my main method.
2- When I had the code in one method - not broken up into pieces - the Boolean was not changing base on my checkLetters method. The output was the same - no matter what the test value was.
I am a java beginner and I would appreciate any advice.
Thank you!
import java.util.Scanner;
public class uniqueLetters
{
boolean isUnique;
char temp;
int i = 0;
String str;
char[] letters;
public static void main(String[] args)
{
testWord testing = new testWord();
}
private void testWord()
{
getArray();
checkLetters();
getStatement();
}
private void getArray()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your word:");
str = keyboard.nextLine();
letters = str.toCharArray();
}
private boolean checkLetters()
{
boolean isUnique = true;
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
return isUnique;
}
private void getStatement()
{
if (checkLetters())
System.out.print("This word has all unique letters");
else
System.out.print("This word has duplicate letters");
}
}
In you loop you do
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
break;
}
}
but as the second loop is also starting at 0, then it will always find a duplicate.
try
for (i = 0; i < letters.length; i++)
{
for (int j = i + 1; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
Also, as you are calling checkLetters from getStatement then you do not need to call it from the testWord method.
Also as testWorld is a method not a class, you should not instantiate it, just call it.

Make a project more OO Java

I've made a 12 by 12 table that runs in the same program, but i'd like to make it OO so that i can put the "public static void main" in another "testfile" and it will still run properly..i'm having some problems with the OO approach and i really need help...This is what my code looks like:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class PlayingArea {
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
int region = input.nextInt();
String letters = "";
while(letters.length() < 2) {
if (region == 4) {
letters= "EFGH";
}
if (region == 3) {
letters= "EFG";
} else if (region == 2) {
letters= "EF";
} else if (region < 2) {
System.out.println("You inputed a wrong value, try again...");
}
}
int N = letters.length();
char [][] letter = new char[12][12];
for (int j = 0; j < letter.length; j++) {
for(int i=0; i < letter.length; i++) {
letter[i][j] = letters.charAt(r.nextInt(N)) ;
}
}
for (char[] letterRow : letter)
System.out.println(Arrays.toString(letterRow));
}
}
if you're relatively new to java then you're doing quite well. Be aware there is an infinite loop in your program (fixed below) if you enter a number outside of 2-4.
Firstly, your class PlayingArea needs some member variables to represent state.
The first one is the String letters (EF or EFG or EFGH), which is initialized via a constructor in the code below.
The second one is the char[][] grid (renamed from letter in your code) which is assigned a value in the populate() method, which puts letters into the grid.
The other method, gridAsString() does just that.
The public static void main can easily now be moved to another class, if you like.
Have fun.
public class PlayingArea {
private String letters;
private char[][] grid;
public PlayingArea(String letters) {
this.letters = letters;
}
public void populate() {
int n = letters.length();
grid = new char[12][12];
Random r = new Random();
for (int j = 0; j < grid.length; j++) {
for (int i = 0; i < grid.length; i++) {
grid[i][j] = letters.charAt(r.nextInt(n));
}
}
}
public String gridAsString() {
StringBuilder sb = new StringBuilder();
for (char[] letterRow : grid) {
sb.append(Arrays.toString(letterRow)).append('\n');
}
return sb.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
String letters = "";
while (letters.length() < 2) {
int region = input.nextInt();
if (region == 4) {
letters = "EFGH";
} else if (region == 3) {
letters = "EFG";
} else if (region == 2) {
letters = "EF";
} else {
System.out.println("You inputed a wrong value, try again...");
}
}
PlayingArea playingArea = new PlayingArea(letters);
playingArea.populate();
System.out.println(playingArea.gridAsString());
}
}

while loop for boolean user input

After getting the program to work for the most part (the help is appreciated :)). All I needed was to add the while loop so the user gets the menu option as many times he wants to. It starts giving me errors as "; expected" at the line where continue switches to false. Here is the code.
import java.io.*;
import java.util.*;
class Matrix {
double[][] element;
int rows, cols;
Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
element = new double[rows][cols];
}
public double getValue(int row, int col) {
return element[row][col];
}
public void setValue(int row, int col, double value) {
element[row][col] = value;
}
public int getNoRows() { // returns the total number of rows
return rows;
}
public int getNoCols() { // returns the total number of cols
return cols;
}
// The methods for the main calculations
public Matrix AddMatrix(Matrix m2) {
int row1 = getNoRows();
int col1 = getNoCols();
Matrix result = new Matrix(row1, col1);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
result.setValue(i, j, this.getValue(i, j) + m2.getValue(i, j));
}
}
return result;
}
public Matrix MultiplyMatrix(Matrix m2) {
if (this.getNoCols() != m2.getNoRows()) {
throw new IllegalArgumentException("matrices can't be multiplied");
}
int row2 = this.getNoRows();
int col2 = m2.getNoCols();
Matrix result = new Matrix(row2, col2);
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
result.setValue(i, j, result.getValue(i, j) + this.getValue(i, j) * m2.getValue(i, j));
}
}
return result;
}
public Matrix TransposeMatrix() {
int row3 = this.getNoCols();
int col3 = this.getNoRows();
Matrix result = new Matrix(row3, col3);
for (int i = 0; i < row3; i++) {
for (int j = 0; j < col3; j++) {
result.setValue(i, j, this.getValue(j, i));
}
}
return result;
}
public void DisplayMatrix() {
for (int i = 0; i < this.getNoRows(); i++) {
for (int j = 0; j < this.getNoCols();
j++) {
System.out.print((this.getValue(i, j)) + " ");
}
System.out.print("\n");
}
}
}
public class Lab1 {
public static void main(String args[]) throws FileNotFoundException {
int choice;
Scanner in = new Scanner(System.in);
Boolean continue = true;
while (continue){
System.out.println("Enter your choice /n");
choice = in.nextInt();
System.out.println("1. Add two matrices \n");
System.out.println("2. Multiplymatrix two matrices \n");
System.out.println("3. Take transpose of a matrix \n");
System.out.println("4. Display a matrix \n");
System.out.println("5. Exit \n");
if (choice == 1) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.AddMatrix(m2);
m3.DisplayMatrix();
}
if (choice == 2) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m2.getNoCols());
m3 = m1.MultiplyMatrix(m2);
m3.DisplayMatrix();
}
if (choice == 3) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.TransposeMatrix();
m3.DisplayMatrix();
}
if (choice == 4) {
System.out.println("Will need to call the DisplyMatrix method for the object \n");
}
if (choice == 5) {
continue = false;
}
else {
System.out.println("Incorrect input. Kindly enter again \n");
}
}
}
public static Matrix MatrixReader() throws FileNotFoundException {
System.out.println("Give the filename for the matrix");
Scanner filescanner = new Scanner(System.in);
Scanner scanner = new Scanner(new File(filescanner.nextLine()));
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
Matrix test = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
test.setValue(i, j, scanner.nextDouble());
}
}
return test;
}
}
Everything looks fairly good except
Boolean continue = true;
and
continue = false;
etc.
continue is a reserved word and may not be used as an identifier. Rename the variable to cont or something similar.
And by the way, I would recommend you to use boolean instead of Boolean in this application.
Also, I believe there is an error in your if-structures:
if (choice == 1)
...
if (choice == 2)
...
if (choice == 5)
...
else
...
The else branch will be taken in all cases when choice != 5 (that is, even when choice is 1, 2, 3, .... So perhaps you want to change it to
if (choice == 1)
...
else if (choice == 2)
...
else if (choice == 3)
...
else
...
Finally, you may also want to consider using a switch for the choice:
switch (choice) {
case 1:
...
break;
case 2:
...
break;
...
default:
...
}
I'm not sure if this may cause conflicts, but "continue" is also a statement within Java. Maybe, by changing the variable name of continue, your problem will be solved. The link attached refers to how continue is used as a statement within Java: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html And what you could also do is make a switch() statement from the if() construction you have, but that's something of personal taste :)
To avoid getting the "m1 is already defined" error, write the switch like that (including the curly braces):
switch (choice) {
case 1: {
...
break;
}
case 2: {
...
break;
}
...
default: {
...
}
}
If you have converted to 'switch' then declare the 'Matrix m1 = null;' just before the switch statement. And in the initialization of each 'case' just use 'm1 = new MatrixReader()'. Do the same for 'm2' variable.

Categories

Resources