Why is my code only outputting "O"? - java

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");
}
}
}

Related

Box pattern made of Xs and Os in 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;
}
}

Finding all the factors of a number in Java?

"Write a program that reads an integer I and displays all its smallest factors in increasing order. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.". At the beginning of the program, the user has to enter an integer identifying how many numbers will be factorized.
import java.util.Scanner;
public class Main {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int size = input.nextInt();
for(int i = 0; i < size; i++){
int a = input.nextInt();
for(int j = 0; j < a; j++){
if(a%j==0){
System.out.println(j);
}
}
}
input.close();
}
}
A Better way of finding all the factors is to find the factors till it's square root.
int n = 120;
for(int i = 2; i * i <= n; ++i)//check below it's square root i <= sqrt(n)
if(n % i == 0){
while(n % i == 0)
{
System.out.println(i);
n /= i;
}
}
A much more effective way is to do it with primes.
There cannot be any other prime factor which is even other than 2 so we can skip the even part
int n = 120;
if(n % 2 == 0)
{
while(n % 2 == 0)
{
System.out.println("2");
n /= 2;
}
}
for(int i = 3; i * i <= n; i += 2)//odd numbers only
{
while(n % i == 0)
{
n /= i;
System.out.println(i);
}
}
A much more efficient way is to use 6*k +- 1 rule,
What is 6*k +- 1 rule?
All prime numbers(except 2 and 3) can be represented by the above formula. Though the reverse might not be true,
Consider 6*6 - 1 = 35 divisible by 5.
If it is not a prime, it will have a prime factor less than it's square root.
So we check only for the numbers which follow the above rule.
int i = 1, n = 120;
//check for 2 and 3
if(n % 2 == 0)
{
while(n % 2 == 0)
{
System.out.println("2");
n /= 2;
}
}
if(n % 3 == 0)
{
while(n % 3 == 0)
{
System.out.println("3");
n /= 3;
}
}
while(true)
{
int p = 6 * i - 1;
if(p * p > n)
break;
if(n % p == 0)
{
while( n % p == 0)
{
n /= i;
System.out.println(p);
}
}
p = 6 * k + 1;
if(p * p > n)
break;
if(n % p == 0)
{
while( n % p == 0)
{
n /= i;
System.out.println(p);
}
}
}
If the numbers are very huge and there are alot of them, Pre-calculate primes can be helpful
I use Sieve to calculate the primes.
int max = 10000007;
boolean[]primes = new boolean[max];
int []nums = new int[max];
int numOfPrimes = 0;
for(int i = 2; i * i < max; ++i)
if(!primes[i])
for(int j = i * i; j < max; j += i)//sieve
primes[j] = true;
for(int i = 2; i < max; ++i)
if(!primes[i])
nums[numOfPrimes++] = i;//we have all the primes now.
int n = 120;
for(int i = 0; i < numOfPrimes; ++i)
{
int p = nums[i];
if(p * p > n)
break;
if(n % p == 0)
{
while(n % p == 0)
{
n /= p;
System.out.println(p);
}
}
}
You should divide the number:
for(int j = 2; j < a; j++){ // start dividing from 2
if(a%j==0){
System.out.println(j);
a/=j; // divide a with j (there is remainder 0 because of condition)
j--; // do j once more
}
}
Try this one:
package bölüm05;
import java.util.Scanner;
public class B05S16 {
public static void main(String[] args) {
Scanner java = new Scanner(System.in);
System.out.println("Bir tamsayı giriniz");
int sayı = java.nextInt();
int i = 2;
while (sayı > 1) {
if (sayı % i == 0) {
sayı = sayı / i;
System.out.print(i + ",");
} else {
i++;
}
}
java.close();
}
}

Prime number generator between 2 nums

I cant figure out which test cases the code provided below fails.
problem:
All submissions for this problem are available.
Shridhar wants to generate some prime numbers for his cryptosystem. Help him!
Your task is to generate all prime numbers between two given numbers.
Input
The first line contains t, the number of test cases (less then or equal to 10).
Followed by t lines which contain two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line. Separate the answers for each test case by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
import java.util.Scanner;
public class Main implements Runnable {
public static void main(String args[]) {
new Main().run();
}
#Override
public void run() {
Scanner sc = new Scanner(System.in);
Integer d;
try {
d = sc.nextInt();
boolean isPrime[] = new boolean[100000];
for (int i = 0; i < d; i++) {
int m = sc.nextInt();
int n = sc.nextInt();
if (n <= 0 || m > n) {
continue;
}
if (m <= 0) {
m = 2;
if (m > n) {
continue;
}
}
if (m == 1) {
m = 2;
}
if (m == 2 && n - m == 0) {
System.out.println(2);
} else {
for (int k = 0; k <= n - m; k++) {
isPrime[k] = true;
}
int sqrt = (int) Math.sqrt(n);
for (int j = 2; j <= sqrt; j++) {
int k = (m % j == 0) ? m / j : (m + j) / j;
for (; k <= n / j; k++) {
if (!(m == 2 && (j * k == 2)) && k != 1) {
isPrime[j * k - m] = false;
}
}
}
for (int a = m; a <= n; a++) {
if (isPrime[a - m]) {
System.out.println(a);
}
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
}
Your problem is with this:
boolean isPrime[] = new boolean[100000];
and this:
for (int k = 0; k <= n - m; k++) {
isPrime[k] = true;
}
because some time n - m = 100000 then you need isPrime[100000] which you didnt allocate so you need to declare isPrime like this:
boolean isPrime[] = new boolean[100001];

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

Special Pythagorean Triplet

What's wrong with my code? It prints 2,2 when the correct answer is clearly 6,8
public static void main(String[] args) {
int a = 1;
int b = 1;
int answer = 0;
int j = 4;
while (j == 4) {
for (a = 1; a <= 10; a++) {
for (b = 1; b <= 10; b++) {
answer = a * a + b * b;
if (answer == 100) {
j = 10;
}
}
}
}
System.out.println(a + " " + b);
}
if(answer == 100);
you have an extra semicolon after your if.
This will cause it to execute the j = 10; no matter what answer equals
You are incrementing a and b at the same time. In your code, the two numbers will always be equal. Also, you are not testing for a match when you exit the loop.

Categories