Box pattern made of Xs and Os in java - java

I'm trying to make a box pattern in java with a pattern that looks like
xoxox
o x
oxoxo
I can get close with alternating x and o on the top and bottom, but there is a line of Os in between that I'm struggling to get rid of. Here is my code so far:
public static String textBoxString(int rows, int cols, char c1, char c2) {
char temp = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (i == 1 || i == rows) {
System.out.print(c1);
temp = c1;
}
if (temp == c1) {
System.out.print(c2);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
String sideString = Integer.toString(rows, cols);
return sideString;
}
Outputs:
xoxoxoxoxo
ooooo
xoxoxoxoxo

Here is an alternate implementation that uses a repeat() method to reduce repetitive code.
This code correctly prints alternating characters around the border. See tests at the end for proof that it works for any combination of odd/even numbers of rows and columns.
Solution for Java 11+:
public static void textBoxString(int rows, int cols, char c1, char c2) {
System.out.println((String.valueOf(c1) + c2).repeat(cols / 2 + 1).substring(0, cols));
String spaces = " ".repeat(cols - 2);
for (int i = 2; i < rows; i++)
System.out.println((i % 2 == 0 ? c2 : c1) + spaces + ((i + cols) % 2 == 0 ? c1 : c2));
System.out.println((rows % 2 == 0 ? String.valueOf(c2) + c1 : String.valueOf(c1) + c2).repeat(cols / 2 + 1).substring(0, cols));
}
Same logic, but for any Java version, using a local repeat() helper method:
public static void textBoxString(int rows, int cols, char c1, char c2) {
System.out.println(repeat(String.valueOf(c1) + c2, cols / 2 + 1).substring(0, cols));
String spaces = repeat(" ", cols - 2);
for (int i = 2; i < rows; i++)
System.out.println((i % 2 == 0 ? c2 : c1) + spaces + ((i + cols) % 2 == 0 ? c1 : c2));
System.out.println(repeat(rows % 2 == 0 ? String.valueOf(c2) + c1 : String.valueOf(c1) + c2, cols / 2 + 1).substring(0, cols));
}
private static String repeat(String s, int count) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < count; i++)
buf.append(s);
return buf.toString();
}
Tests
textBoxString(3, 5, 'x', 'o');
textBoxString(4, 5, 'x', 'o');
textBoxString(4, 6, 'x', 'o');
textBoxString(5, 6, 'x', 'o');
Outputs
xoxox
o o
xoxox
xoxox
o o
x x
oxoxo
xoxoxo
o x
x o
oxoxox
xoxoxo
o x
x o
o x
xoxoxo

I hope you need something like this
public static String textBoxString(int rows, int cols, char c1, char c2) {
char temp;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (1 == i || rows == i) {
System.out.print(c1);
System.out.print(c2);
} else if (1 == j) {
System.out.print(c1 + " ");
} else if (cols == j) {
System.out.print(" " + c2);
} else {
System.out.print(" ");
}
}
temp = c1;
c1 = c2;
c2 = temp;
System.out.println();
}
return Integer.toString(rows, cols);
}

I'd write it as:
public static String textBoxString(int rows, int cols, char c1, char c2) {
String box = "";
boolean firstChar = true;
for(int row=1; row<=rows; row++){
for(int col=1; col<=cols; col++) {
box = box + ((row==1 || row==rows || col==1 || col==cols) ? (firstChar ? c1 : c2) : " ");
firstChar = !firstChar;
}
box = box + System.lineSeparator();
}
return box;
}

This flow will solve your problem :
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static void main(String[] args) {
var result = textBoxString(4,6,'x','o');
System.out.println("Hello world!");
}
public static String textBoxString(int rows, int cols, char c1, char c2) {
char temp = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
char toPrint = j%2==0?c1:c2;
boolean isEmpty=true;
if ((i == 1 || i == rows) || (i >1 && i < rows &&(j==1 || j==cols))) {
isEmpty=false;
}
if (!isEmpty) {
System.out.print(toPrint);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
String sideString = Integer.toString(rows, cols);
return sideString;
}
}

Related

I get java.lang.StringIndexOutOfBoundsException when translating c++ code into java code

I'm trying to solve this problem
https://vjudge.net/problem/UVALive-6805
I found solution but in c++ , Can anybody help me converting it to java code. I'm very newbie to programming
I tried a lot of solutions but non of them work.
Please I need help in this if possible
I don't know for example what is the equivalent for .erase function in c++ in java
Also is is sbstr in c++ provide different result from java ?
#include <iostream>
#include <string>
using namespace std;
int syllable(string word)
{
int L = word.size();
int syllable;
if (L>=7)
{
syllable = 3;
}
else if (L==6)
{
int indicator = 0;
for (int k=0; k<=L-2; k++)
{
string subword = word.substr(k, 2);
if (subword == "ng" || subword == "ny")
{
indicator++;
}
}
if (indicator == 0)
{
syllable = 3;
}
else
{
syllable = 2;
}
}
else if (L == 4 || L == 5)
{
syllable = 2;
}
else if (L == 3)
{
char Char = word[0];
if (Char=='a' || Char=='A' || Char=='e' || Char=='E' || Char=='i' || Char=='I' || Char=='o' || Char=='O' || Char=='u' || Char=='U')
{
syllable = 2;
}
else
{
syllable = 1;
}
}
else
{
syllable = 1;
}
return syllable;
}
int main()
{
string word;
int T;
cin >> T;
for (int i=1; i<=T; i++)
{
int syl[] = {0, -1, -2, -3};
string rhy[] = {"a", "b", "c", "d"};
int verse = 0;
int stop = 0;
while (stop == 0)
{
cin >> word;
int L = word.size();
char end = word[L-1];
if (end == '.')
{
stop = 1;
}
if (word[L-1] == ',' || word[L-1] == '.')
{
word = word.erase(L-1, 1);
L = word.size();
}
if (verse<=3)
{
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.')
{
if (verse<=3)
{
rhy[verse] = word.substr(L-2, 2);
}
verse++;
if (verse<=3)
{
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k=0; k<4; k++)
{
if (syl[k] >= 8 && syl[k] <= 12)
{
A = A + 10;
}
}
for (int k=0; k<2; k++)
{
if (rhy[k] == rhy[k+2])
{
B = B + 20;
}
}
for (int k=0; k<2; k++)
{
if (syl[k] == syl[k+2])
{
C = C + 10;
}
}
if (verse > 4)
{
D = (verse - 4) * 10;
}
int E = A + B + C - D;
cout << "Case #" << i << ": " << A << " " << B << " " << C << " " << D << " " << E << endl;
}
}
here is my trying
import java.util.*;
public class First {
public static int syllable(String word) {
int L = word.length();
int syllable;
if (L >= 7) {
syllable = 3;
} else if (L == 6) {
int indicator = 0;
for (int k = 0; k < L - 3; k++) {
String subword = word.substring(k, 2);
if (subword == "ng" || subword == "ny") {
indicator++;
}
}
if (indicator == 0) {
syllable = 3;
} else {
syllable = 2;
}
} else if (L == 4 || L == 5) {
syllable = 2;
} else if (L == 3) {
char Char = word.charAt(0);
if (Char == 'a' || Char == 'A' || Char == 'e' || Char == 'E' || Char == 'i' || Char == 'I' || Char == 'o'
|| Char == 'O' || Char == 'u' || Char == 'U') {
syllable = 2;
} else {
syllable = 1;
}
} else {
syllable = 1;
}
return syllable;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word;
int T;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
int syl[] = { 0, -1, -2, -3 };
String rhy[] = { "a", "b", "c", "d" };
int verse = 0;
int stop = 0;
while (stop == 0) {
word = sc.next();
int L = word.length();
char end = word.charAt(L-1);
if (end == '.') {
stop = 1;
}
if (word.charAt(L-1) == ',' || word.charAt(L-1) == '.') {
word.substring(L-1, 1);
L = word.length();
}
if (verse <= 3) {
syl[verse] = syl[verse] + syllable(word);
}
if (end == ',' || end == '.') {
if (verse <= 3) {
rhy[verse] = word.substring(L - 2, 2);
}
verse++;
if (verse <= 3) {
syl[verse] = 0;
}
}
}
int A = 0, B = 0, C = 0, D = 0;
for (int k = 0; k < 4; k++) {
if (syl[k] >= 8 && syl[k] <= 12) {
A = A + 10;
}
}
for (int k = 0; k < 2; k++) {
if (rhy[k] == rhy[k + 2]) {
B = B + 20;
}
}
for (int k = 0; k < 2; k++) {
if (syl[k] == syl[k + 2]) {
C = C + 10;
}
}
if (verse > 4) {
D = (verse - 4) * 10;
}
int E = A + B + C - D;
System.out.println("Case #" + i + ": " + A + " " + B + " " + C + " " + D + " " + E);
}
}
}
The Exception is thrown by your second and your third call of String substring method. Your beginIndex is higher than your endIndex. As you can see in here https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int) beginIndex always has to be lower than the endIndex.
Before answering your question, there are some important points to mention in regards to Strings and Java in general.
Strings are immutable (This also applies to C++). This means that no method called on a String will change it, and that all methods simply return new versions of the original String with the operations done on it
The substring method in java has two forms.
One takes in beginIndex and returns everything from beginIndex to str.length() - 1 (where str represents a String)
The other takes in the beginIndex, and the endIndex, and returns everything from beginIndex to endIndex - 1. The beginIndex should never be larger than endIndex otherwise it throws an IndexOutOfBoundsException
C++'s substring method (string::substr()) takes in the beginning "index" and takes in the number of characters after it to include in the substring. So by doing substr(L-2, 2) you get the last two characters of the string.
Java will never allow you to go out of bounds. That means you need to constantly check whether you are within the bounds of anything you are iterating through.
With all this in mind, I would go and verify that all of the substring() method calls are returning the proper range of characters, and that you are properly reassigning the values returned from substring() to the proper variable.
To mimic C++'s string::erase(), depending on what part of the word you want to erase, you want to get the substring of the part before and the substring of the part after it and add them together.
Ex. Lets say I have a String line = "I do not like the movies"; Since it is impossible for anyone to not like movies, we want to cut out the word not
We do this by doing what I said above
String before = line.substring(0, 5); // This gives us "I do " since it goes up to but not including the 5th index.
String after = line.substring(5 + 3); // This gives us the rest of the string starting after the word "not" because not is 3 characters long and this skips to the 3rd index after index 5 (or index 8)
line = before + after; // This'll add those two Strings together and give you "I do like the movies"
Hope this helps!

Why does my code not work when a character is in the second row of the array?

I have some code with a method that is trying to return the opposing character label of a 2d array's position.
Let's suppose the array and it's labels for each position are like below:
{{3,3,3,3}, {3,3,3,3}}
a,b,c,d e,f,g,h
If b is entered, f is returned. I have it working right if a, b, c, or d is entered, but it doesn't work right if e, f, g, or h is entered and I can't figure out why.
public class ByteTest {
public static void main(String[] args) {
int[][] testArray = {{3,3,3,3}, {3,3,3,3}};
// a b c d e f g h
char slectdPit = 'e';
int total = (int)slectdPit;
int total97 = total - 97;
System.out.println(myGetOpposingPit(slectdPit, testArray));
}
public static char myGetOpposingPit(char b, int[][] ints) {
char retChar = 'z';
int retVal = 0;
int charPosi = 0;
int total97 = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < ints[0].length; j++) {
charPosi = (int)b;
total97 = charPosi - 97;
if (total97 <= ints[0].length) {
if (total97 == j) {
retVal = (charPosi + ints[0].length);
retChar = (char)retVal;
}
}
else if (total97 > ints[0].length) {
if (total97 == (j + (ints[0].length))) {
retVal = (charPosi - ints[0].length);
retChar = (char)retVal;
}
}
}
}
return retChar;
}
}
I've made an if statement
else if (total97 > ints[0].length) {
if (total97 == (j + (ints[0].length))) {
retVal = (charPosi - ints[0].length);
retChar = (char)retVal;
}
That's supposed to get find labels that are in the second row of the array, and assign returnedChar with characterPosition - array row length, so if the character ran through myGetOpposingPit is g, it'd be charPosi (103) minus ints[0].length (4), equaling 99, which gets ascii converted into 'c'.
Doesn't work though, z gets returned. So one of my if statements isn't running or something.
Your logic seems to be incorrect for when total97 == ints[0].length. I changed the branch that gets executed when they are equal:
public static char myGetOpposingPit(char b, int[][] ints) {
char retChar = 'z';
int retVal = 0;
int charPosi = 0;
int total97 = 0;
charPosi = (int)b;
total97 = charPosi - 97;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < ints[0].length; j++) {
if (total97 < ints[0].length) {
if (total97 == j) {
retVal = (charPosi + ints[0].length);
retChar = (char)retVal;
}
} else if (total97 >= ints[0].length) {
if (total97 == (j + (ints[0].length))) {
retVal = (charPosi - ints[0].length);
retChar = (char)retVal;
}
}
}
}
return retChar;
}
I also moved the total97 assignment out of the loop. It doesn't change so it doesn't need to be calculated each iteration.

How to achieve array two-column exchange?

We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
all code
package ubung;
import java.util.Random;
//-------------------------------------------------------------- a)
public class Sudoku {
final int n = 3;
final int gridsize = n*n;
int[][] field = new int[gridsize][gridsize];
Random random = new Random();
public Sudoku() {
int[] firstRow = {1,2,3,4,5,6,7,8,9};
//h): int[] firstRow = randomRow();
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
field[i][j] = (i*n + i/n + j) % gridsize + 1;
//h): field[i][j] = firstRow[(i*n + i/n + j) % gridsize];
System.out.println(this);
}
//------------------------------------------------------------- g)
public Sudoku(int permutationCount) {
this();
randomPermutation(permutationCount);
}
//-------------------------------------------------------------- b)
/**Die Methode gibt ein Sudoku-Objekt als einen String zurueck
* #return der String eines Sudoku-Objektes
*/
public String toString() {
String str = line(25);
for(int i = 0; i < 9; i++){
str += "|";
for(int j = 0; j < 9; j++){
str += " " + get(i,j);
if(j == 2 || j == 5 || j == 8)
str += " |";
}
str += "\n";
if(i == 2 || i == 5 || i == 8){
str += line(25);
}
}
return str;
}
/**
* Getter for single entries
*/
private String get(int i, int j) {
if(i < 0 || i > gridsize + 1 || j < 0 || j > gridsize + 1) {
return " ";
}
int m = field[i][j];
if(m == 0)
return " ";
return ""+m;
}
private String line(int n){
String str = "";
for(int i = 0; i < n; i++)
str += "-";
return str+"\n";
}
//-------------------------------------------------------------- c)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions. ?????????????????????????
*/
private void permutateRows(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
for(int i = 0; i < gridsize; i++) {
int temp = field[i][a-1];
field[i][a-1] = field[i][b-1];
field[i][b-1] = temp;
}
}
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions. ????????????????????
*/
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
//-------------------------------------------------------------- d)
/**
* Two stacks are swapped. This produces 3! as much solutions.
*/
private void permutateStacks(int a, int b) {
if(b < a) {
permutateStacks(b,a);
return;
}
if(a == 1 && b == 2) {
permutateColumns(1,4);
permutateColumns(2,5);
permutateColumns(3,6);
}
else if(a == 1 && b == 3) {
permutateColumns(1,7);
permutateColumns(2,8);
permutateColumns(3,9);
}
else if(a == 2 && b == 3) {
permutateColumns(4,7);
permutateColumns(5,8);
permutateColumns(6,9);
}
}
/**
* Two bands are swapped. This produces 3! as much solutions.
*/
private void permutateBands(int a, int b) {
if(b < a) {
permutateBands(b,a);
return;
}
if(a == 1 && b == 2) {
permutateRows(1,4);
permutateRows(2,5);
permutateRows(3,6);
}
else if(a == 1 && b == 3) {
permutateRows(1,7);
permutateRows(2,8);
permutateRows(3,9);
}
else if(a == 2 && b == 3) {
permutateRows(4,7);
permutateRows(5,8);
permutateRows(6,9);
}
}
//-------------------------------------------------------------- e)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions.
*/
private void permutateRows() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateRows(a+block*3,b+block*3);
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions.
*/
private void permutateColumns() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateColumns(a+block*3,b+block*3);
}
private void permutateStacks() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateStacks(a,b);
}
private void permutateBands() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateBands(a,b);
}
//-------------------------------------------------------------- f)
/**
* The matrix is transposed. This produces double as much solutions.
*/
private void transpose() {
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < i; j++) {
int temp = field[j][i];
field[j][i] = field[i][j];
field[i][j] = temp;
}
}
//-------------------------------------------------------------- g)
private void randomPermutation(){
switch(random.nextInt(5)) {
case 0: permutateRows(); break;
case 1: permutateColumns(); break;
case 2: permutateStacks(); break;
case 3: permutateBands(); break;
case 4: transpose();
default:
}
}
private void randomPermutation(int n){
for(int i = 0; i < n; i++)
randomPermutation();
}
//-------------------------------------------------------------- h)
/**
* Returns random row of digits. Used to relabel digits in the initial matrix
* This yields 9! as much solutions.
*/
private int[] randomRow(){
boolean[] used = new boolean[gridsize];
int[] row = new int[gridsize];
for(int i = 0; i < gridsize; i++) {
int candidate = random.nextInt(gridsize);
if(!used[candidate]){
used[candidate] = true;
row[i] = candidate+1;
}
else {
i--;
}
}
return row;
}
//-------------------------------------------------------------- i)
private void hide(int n) {
if(n < 0)
n = 0;
if(n > 81)
n = 81;
for(int k = 0; k < n; k++) {
int i = random.nextInt(9); //在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值。
int j = random.nextInt(9);
if(field[i][j] != 0)
field[i][j] = 0;
else
k--;
}
}
/*****************************************/ //gegeben
public static void main(String[] args){
Sudoku s = new Sudoku(100000);
System.out.println(s);
s.hide(50);
System.out.println(s);
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
If we notate the indices of the 2D array as field[x][y], the provided solution code uses x as the column index and y as the row index. It is important to note that the provided method is not the only correct solution. It would be just as correct to implement x as the row index and y as the column index, so long as the methods were implemented correctly.

Making a hollow diamond with a word in it

What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a

Why is my code only outputting "O"?

public class checkerBoard
{
public static void main(String[] args)
{
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++)
{
for (int c = 1; c <= n; c++)
{
if (c+r % 2 == 0)
System.out.print(x);
else
System.out.print(o);
if (c == n)
System.out.print("\n");
}
}
}
}
It should be printing
XO
OX
XO
OX
But instead it prints
OO
OO
OO
OO
It's probably a really obvious solution but I'm new to this (obviously) and can't figure out what I did wrong.
This is Java, by the way.
Try changing c+r % 2 to (c+r) % 2.
% takes precedence over +.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Try changing if (c+r % 2 == 0) to if((c+r) % 2 == 0)
Enclose your c+r inside parenthesis because % operator has precedence over + operator which is causing modulus to be executed before sum and causing error.
public class checkerBoard
{
public static void main(String[] args)
{
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++)
{
for (int c = 1; c <= n; c++)
{
if ((c+r) % 2 == 0)
System.out.print(x);
else
System.out.print(o);
if (c == n)
System.out.print("\n");
}
}
}
}
The problem is that % takes precedence over +. So, you're code,finally, must look like this :
public class checkerBoard {
public static void main(String[] args) {
int m = 6; //m is rows
int n = 2; //n is columns
char o = 'O';
char x = 'X';
for (int r = 1; r <= m; r++) {
for (int c = 1; c <= n; c++) {
if ((c+r) % 2 == 0){ //% takes precedence over +
System.out.print(x);
} else {
System.out.print(o);
}
}
System.out.print("\n");
}
}
}

Categories