Java Array Help Needed - java

I am building a Java Array where the odd columns will output the #1 and the even columns will output the #0. Here is what i have so far. I'm certain my mistake is trivial but if you could help it would be greatly appreciated!
import java.util.Scanner;
public class TestArray2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int [][] a = new int[5][5];
for(int i=0; i<a.length;i++){
for(int j=0;j<a[0].length;j++){
int x = j;
if(x%2 == 0){
a[i][j] = 0;
}
else {
a[i][j] = 1;
}
}
input.close();
}
}
public class Array2 {
public static void printArray(int[][]a){
for(int i=0;i<a.length;i++){
for(int j=0; j<a[0].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
Array2.printArray(a);
}
}
Array Code

This should work, I skipped the second class
public class TestArray2 {
public static void main(String[] args){
int [][] a = new int[5][5];
for(int i=0; i<a.length;i++){
for(int j=0;j<a[i].length;j++){
int x = j;
if(x%2 == 0){
a[i][j] = 0;
}
else {
a[i][j] = 1;
}
}
}
printArray(a);
}
public static void printArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}

Actually you have two different problems. The first one is that you are using a matrix not an array. The second one is that you are trying to call the method on the second class when it does not have the a variable defined for that.
Try the following:
import java.util.Scanner;
public class TestArray2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int [] a = new int[input];
for(int i=0; i<a.length;i++){
if(i%2 == 0){
a[i] = 0;
} else {
a[i] = 1;
}
}
input.close();
printArray(a);
}
public static void printArray(int[]a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}

Related

Nested loop in while

I created a nested loop using For, here is the program code and the ouput, then I tried the while loop and get the different result:
For:
public class ForBersarang {
public static void main(String[] args){
int a = 5;
for(int i = 0; i<=a; i++){
for(int j = 0; j<=i; j++){
System.out.print("*");
}
System.out.println("");
}
}
While
public class WhileBersarang {
public static void main(String[] args){
int i = 0;
int a = 5;
int j = 0;
while (i<=a) {
while (j <= i) {
System.out.print("*");
j++;
}
i++;
System.out.println("");
}
}
Your problem is where you define j:
public class MyClass {
public static void main(String args[]) {
int i = 0;
int a = 5;
while (i<=a) {
//here
int j = 0;
while (j <= i) {
System.out.print("*");
j++;
}
i++;
System.out.println("");
}
}
}

ArrayIndexOutOfBoundsException when trying to find the determinant of a 2D Array/Matrix

this is my first Stack Overflow post, and I am fairly new to java, so I may not initially comprehend some of the feedback you give me.
With this program, I am supposed to find the determinant of a matrix recursively with a size determined by the user. When I do so, however, I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Determinant.Copy<Determinant.java:55>
at Determinant.det<Determinant.java:31>
at Determinant.main<Determinant.java:15>
I understand what this error means, but I don't understand why it's happening.
Here are the classes I am using (both printmatrix and the main method were written by my teacher, I had to complete the Copy and det methods):
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
matrix[i][j] = (int)(Math.random()*40)-20;
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
int[][] C = new int[B.length-1][B.length-1];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
The error occurs at the else statement in Copy and temp1 = Copy(temp, i).
I am confused, as if either j or k = 1, shouldn't that be a position in the array? What am I missing?
The size of C array in method copy, should be same as B array.
Reason: You are copying B array into C array, they should have same size.
Try the following:
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
matrix[i][j] = (int) (Math.random() * 40) - 20;
}
}
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
//The C array size should be same as B
int[][] C = new int[B.length][B[0].length];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
Hope this explains, enjoy!
You should declare your matrix in Copy function in this way:
int[][] C = new int[B.length][B[0].length];
Otherwise you are declaring a matrix without a row and column. The fact that you start to use from 0 doesn't mean you should declare one row in less!

Creating a Christmas Tree using for loops

I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:
for(int i=1;i<=10;i++){
for(int j=10;j>i;j--){
System.out.println(" ");
}
for(int k=1;k<=i;k++){
System.out.print("*");
}
for(int l=10;l<=1;l++){
for(int h=1;h<=10;h++){
System.out.print(" ");
}
}
System.out.println();
}
What I am trying to do is:
*
***
*****
*******
Try this much simpler code:
public class ChristmasTree {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i; j++)
System.out.print(" ");
for (int k = 0; k < (2 * i + 1); k++)
System.out.print("*");
System.out.println();
}
}
}
It uses 3 loops:
first one for the number of rows,
second one for printing the spaces,
third one for printing the asterisks.
You can do it with simple logic
for (int i = 0; i < 4; i++)
System.out.println(" *******".substring(i, 4 + 2*i));
import java.util.Scanner;
public class cmastree{
public static void main (String[]args){
Scanner keyboard=new Scanner (System.in);
int j;
System.out.println ("Enter a number");
j=keyboard.nextInt();
/*take the above part out and change the j variable if you want to set
the size*/
for(int i=1; i<=j; i+=2){
int numSpaces = (j-i)/2;
for (int k=0; k<numSpaces; k++){
System.out.print(" ");
}
for(int k=0; k<numSpaces; k++){
System.out.print("*");
}
System.out.println();
}
}
}
public class ChrismasTree {
public static void main(String[] args) {
int sizeOfTree = 9;
double remainderVal = sizeOfTree % 2 ;
double ans = sizeOfTree / 2 ;
if (remainderVal == 0) {
System.out.println("Invalid number enter 9,19 calculat rest yourself u looser ..");
System.exit(0);
}
int middlePos = (int) Math.round(ans + .5);
for (int i = 0; i <= sizeOfTree; i++) {
int lStar = middlePos - i;
int rStar = middlePos + i;
if (lStar < 1) {
break;
}
printleaves(lStar, rStar, sizeOfTree);
}
}
public static void printleaves(int a,int b, int size){
System.out.println();
for (int i = 1; i <= size; i++) {
if (i > a && i < b ){
System.out.print("*");
}else System.out.print(" ");
}
}
}
public class Stars {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter Row/Column Value::");
int i,j,k,n;
n=s.nextInt();
for(i=1; i<n; i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n+(n/2); i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n-(n/2); i++){
for(j=n+(n/2); j>1; j--){
System.out.print(" ");}
for(k=n/2; k<=(n/2)+1; k++){
System.out.print("*");}
System.out.println("");
}
}
}
public class ChristmasTree {
public static void printStars(int number) {
for (int i = 1; i <= number; i++) {
System.out.print("*");
}
System.out.println("");
}
public static void printSpaces(int number) {
for (int i = 0; i < number; i++) {
System.out.print(" ");
}
}
public static void christmasTree(int height) {
for (int i = 1; i <= height; i++) {
printSpaces(height - i);
printStars(i + (i - 1));
}
}
public static void main(String[] args) {
// int x = pick some number, but not TOO big )))
christmasTree(x);
}
}
def fist(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def second(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def stem(m)
k=11
for i in range(0,5):
for j in range(0,k):
print(end=" ")
for j in range(0,3):
print("*",end=" ")
print()
first(7)
second(7)
steam(3)

A program that prints the following pattern

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

How to find the Odd and Even numbers in an Array?

Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?
public class Scores {
private int[] numbers;
public Scores(int[] numbersIn) {
numbers = numbersIn;
}
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
int[] evens = new int[numberEvens];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evens[count] = numbers[i];
count++;
}
}
return evens;
}
public int[] findOdds() {
int numberOdds = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] % 2 == 1) {
odds[count] = numbers[i];
count++;
}
}
return odds;
}
public double calculateAverage() {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public String toString() {
String result = "";
for (int i = 0; i < numbers.length; i++) {
result += numbers[i] + "\t";
}
return result;
}
public String toStringInReverse() {
String result = "";
for (int i = numbers.length - 1; i >= 0; i--) {
result += numbers[i] + "\t";
}
return result;
}
}
You're problem is in counting how many even numbers you have
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i] to the if statement
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
numberEvens++;
}
}
looks like you've got the same problem with odd count
'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like
if (numbers[i] % 2 == 0) {
numberEvens++;
}
then it should work. Thanks
Try This Code
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number Elements in Array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("enter Elements ");
for(int i=0; i<n; i++) {
arr[i]=s.nextInt();
}
int [] odd = filterOdd(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Odd" + odd[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
int [] even = filterEven(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Even" + even[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
}
public static int[] filterOdd(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
l++;
}
}
int k[]=new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
k[j] = a[i];
j++;
}
}
return k;
}
public static int[] filterEven(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
l++;
}
}
int k[] = new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
k[j] = a[i];
j++;
}
}
return k;
}
}
public class Array {
public static void main(String[] args) {
// TODO code application logic here
//Array declaration and value asign
int number[]=new int[]{1,2,3,4,5,6,7,8,9};
// for loop to move number
for(int p=0;p<number.length;p++)
{
// check number is even or odd??
if(number[p]%2==0)
System.out.println(number[p]+ " is Even number");
else
System.out.println( number[p]+" is odd umber");
}
}
}
Odd array one columns and another columns even array
public class OddEven {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7,8};
int ss[]=new int[10];
int odd[]=new int[10];
int i;
int k;
for( i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
ss[i]=arr[i];
System.out.print(""+ss[i]);
System.out.print(" ");
}
if((arr[i]%2)!=0)
{
odd[i]=arr[i];
System.out.print(""+odd[i]);
System.out.print(" ");
}else
{
System.out.println(" ");
}
}
}
}
========================================output==============================
1 2
3 4
5 6
7 8

Categories