Make a diagonal using zero for integer print in Java - java

i have a problem with my code. I'm making a program that should display like this:
0 2 3 4
5 0 7 8
9 10 0 11
12 13 14 0
Here's my code:
int rows = 4, count1=1, count2=4;
for(int i=1; i<=rows; i++){
for(int j=1; j<=rows; j++){
if(j==count1){
System.out.printf("0");
}else{
System.out.print(count1);
}
}
if(i<=rows){
count1++;
count2--;
}
System.out.printf("\n");
}
But the output shown is like this:
0 1 1 1
2 0 2 2
3 3 0 3
4 4 4 0
Can somebody tell me what is wrong with my code? Thank you

Use a counter (e.g. count in the code given below) initialized with 1 to print the values. Print 0 when i==j. Increase the counter whether you print the value of the counter or 0.
Do it as follows:
public class Main {
public static void main(String[] args) {
int rows = 4, count = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows; j++, count++) {
if (i == j) {
System.out.printf("%3d", 0);
} else {
System.out.printf("%3d", count);
}
}
System.out.printf("\n");
}
}
}
Output:
0 2 3 4
5 0 7 8
9 10 0 12
13 14 15 0

I can't see a need for two counters. Increment count1 on EVERY iteration of your inner loop. Replace the first condition with if (j == i).

Related

Irrelevant content in java compilation

Can someone be so kind to let me know why the heck javac is printing extra lines with zeros when executed the following lines of code? I have intentionally printed the number of possible lines in the first line, which is exactly equal to the number of nonzero lines. Any advice?
Code:
int[] fa = new int[15];
int[][] sa = new int[100][3];
int a=0, b=0;
for(int i=0; i<15; i++){
fa[i] = i+1;
}
for(int i=0; i<fa.length; i++){
for(int j=i+1; j<fa.length; j++){
for(int k=j+1; k<fa.length; k++){
if(fa[i]+fa[j]+fa[k]==15){
sa[a][0] = fa[i];
sa[a][1] = fa[j];
sa[a][2] = fa[k];
a++;
}
}
}
}
System.out.println(a);
for(int i=0; i<sa.length; i++){
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
The output:
12
1 2 12
1 3 11
1 4 10
1 5 9
1 6 8
2 3 10
2 4 9
2 5 8
2 6 7
3 4 8
3 5 7
4 5 6
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
To print you are iterating on sa:
for(int i=0; i<sa.length; i++){
And at the beginning you stated it has 100 rows (default values to 0):
int[][] sa = new int[100][3];
It shows those 100 rows independently of what you did on your second for with fa.
Try with:
for(int i=0; i<a; i++){
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
You are printing the content of the entire sa regardless of how many items you have added to it. The first 12 items print correctly, while the remaining items print the initial values of int[3] arrays, which happen to be zeros.
You can fix this by iterating up to a items, like this:
for(int i=0; i < a; i++) {
// ^^^
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
Alternatively, you could switch to using lists in place of arrays. Since lists grow dynamically, you would be able to avoid this problem altogether:
class Triple {
private final a, b, c;
public Triple(int a, int b, int c) {this.a=a; this.b=b; this.c=c;}
public int getA() { return a; }
public int getB() { return b; }
public int getC() { return c; }
}
List<Triple> sa = new ArrayList<>();
...
if(fa[i]+fa[j]+fa[k]==15){
sa.add(new Triple(fa[i], fa[j], fa[k]));
}
...
for (Triple t : sa) {
...
}

How the value of a variable j increments to 6

Actually the purpose of the whole code is to get input values (0 or 1) in an array then check entered array for 6 continuous 0's then insert '1'after each 6 consecutive 0's. I found that this block
if(j>5){
shift(i+6);
bits[i+6] = 1;
count+=1;
System.out.println(count);
}
is executed even if there is no 6 consecutive 0's in the entered array. Then to check the problem. I added this statement
System.out.println("ABHINAV " + j );
and here is output:-
Entered Bits are:
1
0
1
0
1
0
1
0
1
0
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 6
I found the problem - the variable 'j' increments to 6 and hence the 'if' block is entered. My Question is:-
How 'j' is getting incremented to 6 (as you can see the last line of the output snap).
How this problem can be solved. What I am doing wrong.
Here is the whole code
class Stuff{
public static final int LENGTH=6;
public int count=0;
int n;
public int bits[] = new int[40];
Scanner inputs = new Scanner(System.in);
Stuff(int x){
n=x;
}
public void input(){
for(int i=0 ; i<n ; i++){
bits[i] = inputs.nextInt();
}
}
public void len_check(){
int j=0;
for(int i = 0 ; i< n ; i++){
j=0;
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
System.out.println("ABHINAV " + j );
if(j>5){
shift(i+6);
bits[i+6] = 1;
count+=1;
System.out.println(count);
}
}
}
public void shift(int u){
for(int i=n ; i>= u ;i--){
bits[i+1] = bits[i];
}
}
public void display(){
for(int i=0 ; i<n+count ; i++){
System.out.println(" " + bits[i]);
}
}
}
class Problem{
public static void main(String args[]){
int n;
Scanner inputs = new Scanner(System.in);
System.out.println("\nEnter bit stream length");
n = inputs.nextInt();
Stuff stuff = new Stuff(n);
System.out.println("Now Enter the bits: ");
stuff.input(); // Enter the bit stream
System.out.println("Entered Bits are: ");
stuff.display();
stuff.len_check();
System.out.println("Altered Bits are: ");
stuff.display();
}
}
It is because the input is only 10 positions long, after the 10 first values the array bits is filled with 0 (standard value).
It is working as programmed, finding 6 0 starting at position 10.
It should stop when reaching the position n - 5, e.g:
...
int j = 0;
for (int i = 0 ; i< n-5 ; i++) {
j = 0;
...
the bits variable was instantiated with the length 40,
public int bits[] = new int[40];
this so the bits[] were an array of zeros with length 40. After that the first ten elements ere replaced by the inputs. Here's the array:
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
value 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ...
This code:
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
when i=9, it increments j 6 times because bits[9] to bits[14] are 0.
bits is an int array of length 40 so it's full of 0 after what you have scanned for System.in.
When i = n-1, you check the last digit you entered which is 0 and all the next one are 0 so j increments to 6.
for(int i = 0 ; i< n ; i++){
j=0;
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
This will just set j to 6 right away. Use an if instead:
if(bits[i+j] == 0 && j<LENGTH){
j+=1;
}

print 2 arrays like matrix for my assignment

I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.

Java Looping Arrays

How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);

Using Nested for loops to make a doubling then halfing pyramid

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw

Categories

Resources