This is what the program is printing:
(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)
What I want it to do is to print ( * ) in replace of (1,1). I know an if statement is involved, but I'm having a hard time trying to figure out the condition I should put.
public class loops {
public static void main(String[] args)
{
int i=1;
for (int k = i-1; i< 4; i++)
{
int j =1;
for (int l = j-1; j < 4; j++)
{
if (k ==i+1 && l == j+1) System.out.print("( * )");
else System.out.print("("+k+","+l+")");
l++;
}
System.out.println();
k++;
}
}
}
The if condition is part of it, but you are also complicating your for loops, try this:
public class loops {
public static void main(String[] args)
{
for (int k = 0; k<3; k++)
{
for (int j = 0; j<3; j++)
{
if (k ==1 && j == 1)
{
System.out.print("( * )");
} else {
System.out.print("("+k+","+j+")");
}
}
System.out.println("");
}
}
}
you should just validate if both values are equal to 1 then print (*) , otherwise the result
Related
class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
for (int i=0; i<a.length; i++)
{
for(int j=0; j<a.length; j++)
{
if ( a[j] == a[i] )
count += 1;
}
System.out.println(a[i]+":"+count);
count = 0;
}
}
Output:
a:2
b:2
c:2
d:1
a:2
b:2
c:2
Here I want to stop the loop until it counts d = 1. but it again prints the same variable? How can i do that?
If you don't want to print the character that has already been printed, you need to maintain it somewhere like in a Set and print only when Set doesn't contain the character and after printing, add it to Set so next time on wards it doesn't get printed.
Change your code to this,
class Mclass {
public static void main(String[] args) {
Set<String> doneSet = new HashSet<String>();
char[] a = { 'a', 'b', 'c', 'd', 'a', 'b', 'c' };
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[j] == a[i])
count += 1;
}
if (!doneSet.contains(String.valueOf(a[i]))) {
System.out.println(a[i] + ":" + count);
doneSet.add(String.valueOf(a[i]));
}
count = 0;
}
}
}
This gives following output as you intend,
a:2
b:2
c:2
d:1
Starting from what you already did, first sort the array then try to count
import java.util.*;
class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
Arrays.sort(a); // sort the array
for (int i=0; i<a.length; i++)
{
for(int j=i; j<a.length; j++)
{
if ( a[j] == a[i] ){
count += 1;
continue;
}
i=j-1;
break;
}
System.out.println(a[i]+":"+count);
count = 0;
}
}
}
output
a:2
b:2
c:2
d:1
Do not print inside loop
Save your count and print outside the loop.
Do something like this:
public class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
Map<String,Integer> output = new HashMap<>();
for (int i=0; i<a.length; i++)
{
for(int j=0; j<a.length; j++)
{
if ( a[j] == a[i] )
count += 1;
}
output.put(Character.toString(a[i]), count);
//System.out.println(a[i]+":"+count);
count = 0;
}
System.out.println(output);
}
}
I am a newbie to java programming and I am working on this excercise from my textbook. The goal is to print a V shape pattern of numbers. From the picture below, you can see what the output should look like. I am having trouble creating the other half of numbers. I have pasted my code down below for reference.
for (int i = 7; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int k = 1; k >= i*2; k++) {
System.out.print(" ");
}
System.out.println(i);
Use the following code (just made a few modifications to your code, did not check its efficiency):
public static void main(String[] args) {
for (int i = 7; i >= 1; i--) {
for (int k = 7; k >= i; k--) {
System.out.print(" "); // Print 7-i number of spaces before start of each line
}
System.out.print(i); // Print i
for (int j = 1; j <= i*2; j++) {
System.out.print(" "); // Print i*2 number of spaces after printing i
}
System.out.println(i); // Print i
}
}
Rather then nesting loops (and iterating backwards), I would decompose the generating of white-space with a method to repeat a given String a given number of times. Like,
private static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining());
}
Then I would prefer a StringBuilder and a single call to println like
public static void main(String[] args) {
int start = 6;
for (int i = 0; i < start; i++) {
int v = start - i;
StringBuilder sb = new StringBuilder();
sb.append(repeat(" ", i)).append(v);
sb.append(repeat(" ", 2 * v)).append(v);
System.out.println(sb);
}
}
I have to code a program to print this output:
1
212
32123
4321234
543212345
I have successfully coded this portion of the pattern:
1
12
123
1234
12345
However, I am not reaching the second portion. Here's my code:
for(int i=1; i<=5; i++) {
for(int j=1; j<=i; j++) {
System.out.print(j);
}
System.out.println();
}
Why not recursive? Just because it's fun ;)
public static void main(String args[]) {
System.out.println(pyramid(5));
}
public static String pyramid(int rank) {
if (rank == 1) {
return "1\n";
}
return pyramid(rank - 1) + mirror(rank) + "\n";
}
public static String mirror(int rank) {
if (rank == 1) {
return "1";
} else {
return rank + mirror(rank - 1) + rank;
}
}
You just need another j for loop before your current j for loop that counts down from 5 to (but not including) 1. Decide whether to print a space or j itself, depending on if j is greater than i.
for (int j=5; j > 1; j--) {
if (j > i)
System.out.print(' ');
else
System.out.print(j);
}
package recAaA;
public class testA {
static void rec(int startVal, int endVal)
{
if(startVal==0)startVal=-2;
if(startVal<-endVal) return;
System.out.print(Math.abs(startVal));
rec(startVal-1,endVal);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int imax=5;
for(int i=1;i<imax+1;i++)
{
for(int j=0;j<imax+1-i;j++)
{
System.out.print(" ");
}
rec(i,i);
System.out.println();
}
}
}
Output:
1
212
32123
4321234
543212345
if you give i to startVal and i+1 to endVal, the output becomes
12
2123
321234
43212345
5432123456
As someone already noted, you can accomplish this easily with a double for-loop, one counting down from i, one counting up:
for(int i=1; i<=5; i++) {
for(int j=i; j>=2; j--) {
System.out.print(j);
}
for(int j=1; j<=i; j++) {
System.out.print(j);
}
System.out.println();
}
You can also accomplish the same thing in a single for loop if you don't print right away. For example you can build an StringBuffer with one, then add the numbers on either side until i==j, and then print outside of the inner loop.
for(int i=1; i<=5; i++) {
StringBuffer buffer = new StringBuffer();
buffer.append(1);
for(int j=2; j<=i; j++) {
buffer.insert(0, j);
buffer.append(j);
}
System.out.println(buffer);
}
Here's code that outputs the numbers; all you have to do is fix the spacing.
for (int i = 1; i <= 9; i++) {
BigInteger b =
BigInteger.TEN.pow(2*i-1)
.subtract(BigInteger.ONE)
.divide(BigInteger.valueOf(9))
.multiply(BigInteger.valueOf(i+1))
.subtract(BigInteger.TEN.pow(i)
.subtract(BigInteger.ONE)
.divide(BigInteger.valueOf(9))
.pow(2));
System.out.println(b);
}
That is, for each integer in the range 1-9, it prints ((102n-1-1)/9)(n+1)-((10n-1)/9)2. Very simple.
/* Basically logic is that in a horizontal line upto the mid ,the number is decrementing and after the mid, the number starts incrementing
*/
public class java {
public static void main(String[] args) throws IOException {
int n;
InputStreamReader io = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(io);
System.out.println("Enter the height in the number of lines vertically");
n = Integer.parseInt(br.readLine());
for (int i = 1; i <= n; i++) {
int k = i;
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print(k);
if (j >= (((2 * i - 1) / 2) + 1))
k++;
else if(j<(2*i-1)/2+1) k--;
}
System.out.println();
}
}
}
I hope this will help !
import java.util.*;
public class test {
public static void main(String[] args) {
int i,j,k,l,n,a;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = n;
for(i=1 ; i<=n ; i++){
for(j=a ; j>1 ; j--){
System.out.print(" ");
}
for(k=i ; k!=0; k--){
System.out.print(k);
}
a--;
for(l=2; l<=i ; l++){
System.out.print(l);
}
System.out.println(" ");
}
}
}
for(int i=1;i<=100; i++) {
for(int j=100;j>i;j--)
System.out.print(" ");
for(int k=i;k>1;k--)
System.out.print(k+" ");
for(int j=1; j<=i; j++)
System.out.print(j+" ");
System.out.println();
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter no ");
int n=in.nextInt();
for(int i=1;i<=n;i++)
{
int l=n-i;
while(l!=0)
{
System.out.print(" ");
l--;
}
for(int j=i;j>=2;j--)
{
System.out.print(j);
}
for(int k=1;k<=i;k++)
{
System.out.print(k);
}
System.out.println();
}
}
}
I want to print an asterisk when i + j equals a specified number, but my code never prints one:
public class A{
public static void main(String[]args){
for (int i = 5; i < 10; i++) {
for (int j = 5; j < 10; j++) {
if ( i == j || ( i+j == 7 )) {
System.out.printf("*");
} else {
System.out.printf("");
}
}
System.out.println();
}
}
}
Well, when you are making the blank, it should be a " ", not a "", otherwise there will be no spaces. And it should be if I + J = 14, not 7, as it will never equal 7.
A good approach to drawing such patterns is to break them into regions/areas and then use various loops and conditional statements to construct those regions.
E.g. An approach to drawing X pattern is divide the X pattern into two parts from half vertically. Now, you can easily think to draw those to parts.
You can take help from this.
public class xpattern {
public static void main(String[] args) {
int totalLines = 11;
for (int i = 0; i < totalLines; i++) {
for(int j = 0; j < totalLines; j++) {
if(i == j || j == (totalLines - (i + 1))) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
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]);
}