Very simple but I cannot seem to figure it out, I simply need to translate the while loops into do-while. Objective is to print 1-9 and 9-1 one as such "1,22,333,4444" etc. Thank you if you help me!
int y = 1;
int x = 1;
while (x < 10) {
y = 1;
while (y <= x) {
y++;
System.out.print(x + "");
}
System.out.println();
x++;
}
int a = 9;
int b = 1;
while (a >=1) {
b = 1;
while (b<= a) {
b++;
System.out.print(a + "");
}
System.out.println();
a--;
}
My attempt prints 1-9 but as single numbers and infinitely runs, but does not print anything after 9 the first time.
int c = 1;
int d =1;
do { System.out.print(c +"");
c++;
System.out.println();
}
while (c<10);{
y=1;
while (d<=c);
}
Looks like we are doing your homework...
public class Test {
public static void main(String[] args) {
int c = 1;
do {
int d =1;
do{
System.out.print(c);
d++;
} while (c>=d);
System.out.println("");
c++;
}
while (c<10);
}
}
This is a basic usage:
x=1;
do{
//hello
x++;
} while(x<=10);
Apply it as you need. We can't really do your homework.
What you want is a nested do-while.
int x = 1;
do {
int p = 0;
do {
System.out.print(x);
}
while(p < x)
System.out.println();
x++;
}
while(x < 10)
But I should probably add a for loop would make a lot more sense here:
for(int x = 0; x < 10; x++)
{
for(int p = 0; p < x; p++)
{
System.out.print(x);
}
System.out.println();
}
As you want to run in infinite loop just use:
do {
int c = 1;
do {
System.out.println(c);
c++;
} while (c < 10);
} while (true);
This will run infinitely and print your desired strings:
StringBuilder result1= new StringBuilder();
StringBuilder result2 = new StringBuilder();
do
{
for(int i = 1; i < 10; i++)
{
for(int j = 0; j < i; j++)
{
result1.append(i);
}
result1.append(",");
}
for(int i = 9; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
result2.append(i);
}
result2.append(",");
}
System.out.println(result1);
System.out.println(result2);
}while(true);
Related
I need to write a program that prints out the following figure:
122333444455555
22333444455555
333444455555
444455555
55555
This is my code:
for (int a = 0; a <= 5; a++)
{
for (int b = 0; b < a; b++)
{
System.out.print(a);
}
}
which prints out 122333444455555
I need to triple nest my for loops, but I'm not sure where else to start. If I could get any hints/tips, that would be greatly appreciated.
I think you have over thought this. I would simplify things and use a different algorithm. Initiate a String and mutate it with one loop. Like,
String s = "122333444455555";
for (int i = 0; i < 5; i++) {
System.out.println(s);
s = s.substring(i + 1);
}
Outputs (as requested)
122333444455555
22333444455555
333444455555
444455555
55555
Alternatively:
for(int a = 1; a <= 5; a++){
for (int b = a; b <= 5; b++) {
for (int c = 1; c <= b; c++) {
System.out.print(b);
}
}
System.out.println();
}
I know that you had your answer, but I have some fun doing this LOL:
public static void main(String[] args)
{
int aux = 0;
for(int i = 1; i <=5 ; i++) {
if(i == 1) {
System.out.print("1");
} else if (i ==2){
System.out.print("22");
}else if (i ==3){
System.out.print("333");
}else if (i ==4){
System.out.print("4444");
}else if (i ==5){
System.out.print("55555\n");
if(aux != 5) {
aux ++;
i = aux;
}
}
}
}
Since you said for loops I assume you meant at least two of them.
for (int i = 1; i <= 5; i++) {
for(int k = i; k <= 5; k++) {
System.out.print((k+"").repeat(k));
}
System.out.println();
}
A more common solution about you issue:
Codes
private static void printStringSequence(int number) {
for (int i = 0; i < number; i++) {
StringBuilder sb = new StringBuilder();
for (int j = i; j < number; j++) {
sb.append(generateRepeateSequence(j + 1));
}
System.out.println(sb.toString());
}
}
private static String generateRepeateSequence(int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < number; i++) {
sb.append(number);
}
return sb.toString();
}
Test Output
printStringSequence(5);
122333444455555
22333444455555
333444455555
444455555
55555
printStringSequence(4);
1223334444
223334444
3334444
4444
So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}
I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing
public class TestProgram {
public static void main(String[] args) {
TestProgram test = new TestProgram();
test.draw(15, 4);
}
public void draw(int x, int y) {
// System.out.println(".");
System.out.println();
int i = 0;
int j = 0;
for (i = 0; i < x; i++) {
System.out.print(".");
// continue;
}
for (j = x; j > y; j--) {
System.out.println(".");
System.out.print("\t\t");
System.out.println(".");
}
for (int k = 0; k <= x; k++) {
System.out.print(".");
}
}
}
How about:
public class TestProgram {
public static void main(String[] args) {
TestProgram test = new TestProgram();
test.draw(15, 4);
}
public void draw(int x, int y) {
System.out.println(generateLine(x, '.'));
for (int i = 1; i< y-1; i++) {
System.out.println("." + generateLine(x-2, ' ') + ".");
}
System.out.println(generateLine(x, '.'));
}
private String generateLine(int x, char character) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < x; i++) {
stringBuilder.append(character);
}
return stringBuilder.toString();
}
}
I am not sure i understood currectly but you're trying to print squares without swing? But you're using system.out.print. Its a bit confusing but if its for learning programming homework from school here you go to make a square with for loops:
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
for (int i = 0; i < height - 2; i++) {
System.out.print("*");
for (int j = 0; j < width - 2; j++) {
System.out.print(" ");
}
System.out.println("*");
}
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
}
But if you want to make rectangles (Because you mentioned swing) you should check java.awt.Rectangle2D and Rectangle:
https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
You can do it in this way:
void rectangleDraw(int x, int y) {
String line1 = new String(new byte[x]).replaceAll("", ".");
String line2 = "." + new String(new byte[x - 2]).replaceAll("", " ") + ".";
System.out.println(line1);
for (int i = x; i > y; i--) {
System.out.println(line2);
}
System.out.println(line1);
}
I have some problem printing a reverse triangle I want to achieve, like this pattern:
******
***
*
But my goal is to achieve that pattern with this numbers:
333221
221
1
So, this is my code so far:
int x = 1;
for(int r=0;r<3;r++)
{
x=x+r;
for(int c=0;c<x;c++)
{
System.out.print("*");
}
x+=1;
System.out.println();
}
Which the output is upright like this:
*
***
******
I want to make the pattern reverse with the numbers as it shown above.
Can anyone give me some idea how to deal with it? Thanks!
This is how i would do it:
for (i = 3; i > 0; i--) {
for (j = i; j > 0; j--) {
for (c = j; c > 0; c--) {
System.out.print(j);
}
}
System.out.println();
}
first loop: you want to print 3 lines;
second loop: each line has i distinct numbers
third loop: print number j j times
You just need to reverse the order of your loops and decrement x instead of incrementing it. I change the code a bit though :
int level = 3;
for(int r=level ; r>0 ; r--) {
for(int c=r ; c>0 ; c--)
for (int x=0 ; x<c ; x++)
System.out.print("*");
System.out.println();
}
int depth = 3;
for (int r = depth + 1; r >= 0; r--) {
for (int c = 0; c < r; c++)
for (int b = 0; b < c; b++)
System.out.print("*");
System.out.println();
}
#Test
public void reverseTriangle(){
int num = 3;
for (int i = num; i > 0; i--) {
this.draw(i);
System.out.println();
}
}
private void draw(int num) {
int total = 0;
for (int i = 0; i <= num; i++) {
total = total + i;
}
for (int i = 0; i < total; i++) {
System.out.print("*");
}
}
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}