Need assistance with looping in java - java

Currently working on some extra problem sets and seem to be stuck with this one. I need to make the following output:
* *
* *
* * * * *
* *
* *
I've got the cross down but i'm having problems with the middle line and was hoping someone could help me figure it out. Heres my code so far (input is set to 5):
public static void drawPlusVersion3(int input){
if (input % 2 != 0) {
for(int c = 0; c < input; c++) {
for(int r = 0; r < input; r++) {
if((c == input / 2) || (r == input / 2))
System.out.print("*");
if ( c == r){
System.out.print("*");
}
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}
Current output:
* *
* *
* * ** * *
* *
* *
Thanks in advance!

You can try:
public static void drawPlusVersion3(int input){
if (input % 2 != 0) {
for(int c = 0; c < input; c++) {
for(int r = input - 1; r >= 0; r--) {
if((c == input / 2) || (r == input / 2) || c == r)
System.out.print("*");
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}

How about this:
for (int i = 0; i < input; i++) {
for (int j = 0; j < input; j++) {
if (j == input / 2 || i == input / 2 || i + j == input - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}

Related

Nested Loops to make shapes

I am having a little trouble with one shape I am currently trying to make here is my code currently:
import java.util.Scanner;
public class Problem2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = 0;
do
{
System.out.print("Enter an odd integer greater than or equal to 5: ");
n = input.nextInt();
}while(n < 5 || n % 2 == 0);
boxWithMinorDiagonal(n);
rightTriangle(n);
printNLetter(n);
fancySquare(n);
}
public static void fancySquare(int n)
{
System.out.println();
int tempRow = 2;
int tempCol = 2;
int tempColDec = n - 2;
int tempRowInc = 2;
for(int row = 1; row <= n; row++)
{
for(int col = 1; col <= n; col++)
{
if(row == 1 || row == n || col == 1 || col == n)
{
if(row == 1 && col == 1 || row == 1 && col == n || row == n && col == 1 || row == n && col == n)
{
System.out.print("#");
}
else
{
System.out.print("*");
}
}
else if(tempRow == row && tempCol == col)
{
System.out.print("+");
tempCol++;
tempRow++;
}
else
{
System.out.print(" ");
}
if(row == tempRowInc && col == tempColDec)
{
System.out.print("+");
tempColDec--;
tempRowInc++;
}
}
System.out.println();
}
}
}
Everything works correctly except my last method "fancySquare" is not printing out how I would like it to. It is currently printing out this shape if the user input is 9:
#*******#
*+ + *
* + + *
* + + *
* ++ *
* + + *
* + + *
*+ +*
#*******#
It should look like this instead
#*******#
*+ +*
* + + *
* + + *
* # *
* + + *
* + + *
*+ +*
#*******#
Try to use named booleans for your checks to make it more understandable.
More common is to use zero based index, but i stick to your version to make it more similar and easier to match for you.
public static void fancySquare(int n) {
System.out.println();
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
final boolean firstRow = row == 1;
final boolean lastRow = row == n;
final boolean firstCol = col == 1;
final boolean lastCol = col == n;
// calc the center
final boolean center = row == (n + 1) / 2 && col == (n + 1) / 2;
// calc the marker
final boolean marker = row == col || n - row + 1 == col;
// we need the # marker at the corners (1,1) || (1,n) || (n,1) || (n,n)
if ((firstRow || lastRow) && (firstCol || lastCol)) {
System.out.print("#");
// we need the * in the first & last column/row which is no corner
} else if (firstRow || lastRow || firstCol || lastCol) {
System.out.print("*");
// we need a # also in the center
} else if (center) {
System.out.print("#");
// we need the plus on the diagonals
} else if (marker) {
System.out.print("+");
// instead we need a space
} else {
System.out.print(" ");
}
}
System.out.println();
}
}

How to print x pattern in Java using for loops?

My goal is to get this output when input is 3:
* *
* *
* *
*
* *
* *
* *
Here is my code:
public static void PrintX (int number) {
for (int i = 0; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
My output when input is 3 is like this and I'm not sure why there is the extra star at the top.
*
* *
* *
* *
*
* *
* *
* *
Your outer loop would work as you expect if you set an initial i value of 1. However, you could also make this a little shorter. First, consider storing the number * 2 + 1. Then you might combine a few lambda expressions with IntStream. Basically, you want to map each possible index to a " " or a "*" - so
public static void PrintX(int number) {
int len = number * 2 + 1;
IntStream.rangeClosed(1, len).forEachOrdered(i -> {
IntStream.rangeClosed(0, len)
.mapToObj(j -> i == j || i + j == len + 1 ? "*" : " ")
.forEachOrdered(System.out::print);
System.out.println();
});
}
Set i = 1 inside outer for loop. Compile and run the example below:
public class TestPrintX {
public static void PrintX (int number) {
for (int i = 1; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
public static void main(String arg[]) {
PrintX(3);
} // end of main method
} // end of class

Finding the diagonals of any random point in a square 2D array

I have to write the code that sets an 8x8 matrix, a chessboard, and then asks the user what row and what column they want to place the queen on. I then have to put a * on each square to which the queen can move. Putting a * on the row and column the queen could move to wasn't difficult but I'm having trouble correctly labeling the diagonals to on which the queen can move. This is the code I have written so far to try and locate the diagonal:
char[][] chessboard = new char[8][8];
System.out.print("What row do you want to place the queen on? ");
int row = console.nextInt();
System.out.print("What column do you want to place the queen on? ");
int column = console.nextInt();
char queen = 'Q';
chessboard[row - 1][column - 1] = queen;
// column and rows
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
if ((i == 2 || j == 6) && chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
if ((row - 1) != 0) {
// left diagonal
for (int i = 0; i < row; i++) {
for (int j = (column - 1 - (row - 1)); ((column - 1) - (row - 1)) <= j && j < column; j++) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
for (int i = (row - 1) + (8 - (column)); i >= row - 1; i--) {
for (int j = 7; j >= (column - 1); j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
// right diagonal
for (int i = 7; i >= row - 1; i--) {
for (int j = (column - 1 - (row - 1)); 0 <= j && j < column; j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
}
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
}
When I put in experimental values, for example row 3 and column 7, I get a really messy output. For the numbers above, I get:
[][][][] * * * []
[][][][] * * * []
* * * * * * Q *
* * * * * [] * *
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
Could someone tell me where I'm going wrong?
* This is a homework question so code only in the answers, please. Thanks!
If it were me, I'd simply loop through each square of the chessboard and test the validity of each square as being one that the queen can move to, of the three possible rules, namely
square.x == queen.x ||
square.y == queen.y ||
|square.x - queen.x| == |square.y - queen.y|
If your square matches any of the above rules, then it's a valid square to move to, otherwise it's not. Omitting the square that the queen currently resides on, of course
square.x != queen.x && square.y != queen.y
Pseudocode:
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
// You could encapsulate these lines in a isValidSquareForQueenMove(x, y) method.
boolean isSquareValid = false;
isSquareValid = isSquareValid || x == queen.x;
isSquareValid = isSquareValid || y == queen.y;
isSquareValid = isSquareValid || Math.abs(queen.x - x) == Math.abs(queen.y - y);
isSquareValid = isSquareValid && x != queen.x && y != queen.y;
// Do stuff here.
}
}

Binary String to Hex String

I want to turn a string of binary to hexadecimal string
For example, I have a length of 24 binary string
"000100000010000000110000"
Convert hex becomes 0x10 0x20 0x30
How can I do?
I made reference to this: http: //stackoverflow.com/questions/25592084/converting-binary-string-to-a-hexadecimal-string-java
But I tried the results are not correct ...
I was wrong in what I ask?
int digitNumber = 1;
int sum = 0;
String binary = "00000001";
for(int i = 0; i < binary.length(); i++)
{
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1)
{
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print("0x"+sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
}
The result is ...
0x00x1
Try this:
Integer.parseInt(binOutput, 2) instead of Integer.parseInt(binOutput)
//Here is my Solution:
package stringprocessing;
/**
*
* #author zayeed
*/
public class StringProcessing {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int index = 0;
String bin = "0000000101100101011011100110011100000001000000000000000010101010010101100110010101100011011010010110110101100001001000000100111001100101011101000111011101101111011100100110101101110011001000000100100001000001010100110010000001001001010100110101001101010101010001010100010000100000010000010010000001010010010001010101000101010101010010010101001001000101010001000010000001010111010001010100010101001011010011000101100100100000010101000100010101010011010101000010000001000110010011110101001000100000010101000100100001000101001000000100011001001111010011000100110001001111010101110100100101001110010001110010000001000011010011110101010101001110010101000100100101000101010100110010111101000001010100100100010101000001010100110011101000100000010100000110100101101110011000010110110000101100001000000100000101011010001110110010000001000001010101000010000000000001111000000011000100110010001110100011000100110011001000000101000001001101001000000100111101001110";
String[] hexString = new String[bin.length() / 4];
for (int i = 0; i < bin.length() / 4; i++) {
hexString[i] = "";
for (int j = index; j < index + 4; j++) {
hexString[i] += bin.charAt(j);
}
index += 4;
}
for (int i = 0; i < bin.length() / 4; i++) {
System.out.print(hexString[i] + " ");
}
// System.out.println("\n" + bin.length());
String[] result = binaryToHex(hexString);
for (int i = 0; i < result.length; i++) {
System.out.print("" + result[i].toUpperCase());
}
System.out.println("");
}
public static String[] binaryToHex(String[] bin) {
String[] result = new String[bin.length];
for (int i = 0; i < bin.length; i++) {
result[i] = Integer.toHexString(Integer.parseInt(bin[i], 2));
}
//return Integer.toHexString(Integer.parseInt(bin[0], 2));
return result;
}
}

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

Categories