I am writing the code to print a matrix on taking user input in the form of n value:
Suppose if,
n= 3
output:
3 3 3
3 0 3
3 1 3
3 2 3
3 3 3
I am getting ArrayIndexOutOfBoundException in the line: a[i][j]=n;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done. TheArrayIndexOutOfBoundsException is aRuntime Exception thrown only at runtime.
Look at this line:
for(int j=0;i<n;j++)
you increment while "i < n" but you increment "j++".
When your j reaches value 3, the inner loop continues, but exceeds the array-length (of 3, because the hightest array-index is actually 2).
(Also on a minor sidenote, it is usually preferrable to write ++i or ++j within for-loop increments. This is not a rule, just easier to read for most oldscool c-Devs). Also consider leaving spaces to inprove readability:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][] = new int[n][n];
int b = 0;
int mid = n / 2 + 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + j == mid) {
a[i][j] = n - b;
b++;
} else {
a[i][j] = n;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
minor correction in a loop
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++) //minor correction here
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
Related
Below is my code for Insertion Sort and i am facing an exception of array indexing.
import java.util.Scanner;
public class Insertion_Sort {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=4;
int ar[]=new int[n];
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
for(int i=1;i<n;i++)
{
int c=ar[i];
int j=i-1;
while(ar[j]>ar[j+1] && j>=0)
{
ar[j+1]=ar[j];
j--;
}
ar[j+1]=c;
}
for(int i=0;i<n;i++)
{
System.out.println(ar[i]);
}
}
}
This is the exception i am getting everytime i run this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at dfsd.Insertion_Sort.main(Insertion_Sort.java:17)
First thing is that you should check j >= 0 first and if that happen check second condition which is ar[j] > ar[i]. but there is another problem ar array is changing during the process and you should use c instead of ar[i] so the condition would be: j >= 0 && ar[j] > c. Here is the working version of your code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 4;
int ar[] = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = sc.nextInt();
}
for (int i = 1; i < n; i++) {
int c = ar[i];
int j = i - 1;
while (j >= 0 && ar[j] > c) {
ar[j + 1] = ar[j];
j--;
}
ar[j + 1] = c;
}
for (int i = 0; i < n; i++) {
System.out.println(ar[i]);
}
}
J>=0 should be the first condition. Also you need to check j<n as you are using j+1 in the check (scenario when i reached n-1) to avoid exceptions.
The logic of insertion sort seems to be incorrect.
I have an issue where it seems like when I try to display my new array full of even numbers from the first array, it only outputs the last value? I don't see where the problem lies within the nested for loop inside my GetEven method?
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int Read(int[] arr) {
Scanner scan = new Scanner(System.in);
int count = 0;
for (int i = 0; i < arr.length; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
if (arr[i] % 2 == 0) {
count++;
}
}
System.out.printf("There are %d even numbers\n", count);
return count;
}
static int[] GetEven(int[] arr, int count) {
int[] evenArr = new int[count];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < count; j++) {
if (arr[i] % 2 == 0) {
evenArr[j] = arr[i];
}
}
}
return evenArr;
}
static void Print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int n = scan.nextInt();
int[] arr = new int[n];
int a = Read(arr);
Print(GetEven(arr, a));
}
}
You'are getting only the last value because due to the inner for loop in the GetEven method: every time you do a full inner loop (you do it for every number in arr) you rewrite the whole evenArr.
So the fix is removing the inner loop:
static int[] getEven(int[] arr, int count) {
int[] evenArr = new int[count];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
evenArr[j++] = arr[i];
}
}
return evenArr;
}
By the way, methods name should be lowercase. Naming conventions
As Ruben said the problem is in your loop. I took the liberty to refactor your code a bit just to show you a better approach to the problem
package allevenproj;
import java.util.*;
public class AllEvenProj {
static int[] read(int size) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter arr[%d]: ", i);
arr[i] = scan.nextInt();
}
return arr;
}
static void print(int[] arr) {
System.out.printf("There are %d even numbers\n", arr.length);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array: ");
int size = scan.nextInt();
print(Arrays.stream(read(size)).filter(x -> x % 2 == 0).toArray());
}
}
import java.util.Scanner;
public class PrintVshape {
public static void main(String [] args){
Scanner inputDevice = new Scanner(System.in);
for(int i=0;i<5;i++){
for(int k=6;k>i;k--){
System.out.print("x");
}
System.out.print("V");
for(int j=7;j>i;j--){
System.out.print("p");
}
System.out.print("V");
System.out.print("\n");
}
}
}
This prints out the following:
xxxxxxVpppppppV
xxxxxVppppppV
xxxxVpppppV
xxxVppppV
xxVpppV
This is a homework problem. It's the x's that I'm stuck on. I need to invert them so they become more instead of fewer.
The loop you have for x says that run it from 6 to i and i moves from 0 to 5;
for(int k=6;k>i;k--){
System.out.print("x");
}
Which means x will be printed 6 times , 5 times .. ..
Correct the loop for x and it will be fine.
You need to loop on k up to some increasing value, such as i, or in this case, i+2, to get the range between two xs in the first row to six xs in the last:
for (int k = 0; k < i+2; k++) {
System.out.print("x");
}
Scanner inputDevice = new Scanner(System.in);
for(int i=0;i<5;i++){
for(int k=0;k<i+2;k++){
System.out.print("x");
}
System.out.print("V");
for(int j=7;j>i;j--){
System.out.print("p");
}
System.out.print("V");
System.out.print("\n");
}
}
result:
xxVpppppppV
xxxVppppppV
xxxxVpppppV
xxxxxVppppV
xxxxxxVpppV
i+2 in k cycle, mean how many times it will print x on beginnig (if you want start with xx then i=0+2)
I am not quite sure, is this the thing you are after now?
public static void main(String[] args) {
int N = 8;
printV(N);
}
private static void printV(int N) {
for (int i = 0; i < N; i++) {
for (int k = 0; k < i; ++k) {
System.out.print("x");
}
System.out.print("V");
for (int j = 0; j < (N - i - 1) * 2; ++j) {
System.out.print("p");
}
System.out.print("V");
for (int k = 0; k < i; ++k) {
System.out.print("x");
}
System.out.print("\n");
}
}
Output:
VppppppppppppppV
xVppppppppppppVx
xxVppppppppppVxx
xxxVppppppppVxxx
xxxxVppppppVxxxx
xxxxxVppppVxxxxx
xxxxxxVppVxxxxxx
xxxxxxxVVxxxxxxx
I want to print number pattern like this..
but, I failed to get this triangle shape,and I am confused how to put spaces to get this shape -->
1
212
32123
4321234
Here's the code i tried so far
public class Ch {
public static void main(String[] args) {
int r =Integer.parseInt(args[0]);
for(int u=1;u<=r;u++)
{
for(int i=u;i>=1;i--)
{
System.out.print(i);
}
for(int i=2;i<=u;i++)
{
System.out.print(i);
}
System.out.println();
}
}
}
output of this code looks-like this
1
212
32123
4321234
Thanks
Just add one more step in you main loop before the other two:
for (int i = u; i < r; i++)
{
System.out.print(" ");
}
This will print spaces to make up for the "missing" numbers.
In regard to Mateusz' comment, look at this answer on how to pad your numbers with spaces to make them equally wide in case you go beyond 9:
static int padding;
public static void main(String[] args)
{
int r = Integer.parseInt(args[0]);
padding = Math.max(1, (int) Math.ceil(Math.log10(r)));
for (int u = 1; u <= r; u++)
{
for (int i = u; i < r; i++)
{
print(" ");
}
for (int i = u; i >= 1; i--)
{
print(i);
}
for (int i = 2; i <= u; i++)
{
print(i);
}
System.out.println();
}
}
private static void print(Object text)
{
System.out.print(String.format("%1$" + padding + "s", text));
}
using 2 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for (int j = 0; j < limit + i; j++) {
if (j < limit -i-1)
System.out.print(" ");
else{
int temp = (limit-j > 0) ? limit-j : j-limit+2;
System.out.print(temp);
}
}
System.out.println();
}
}
}
using 4 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for(int j=0; j<limit-i; j++){
System.out.print(" ");
}
for(int j=0; j<=i; j++){
System.out.print(i-j+1);
}
for(int j=i; j>0; j--){
System.out.print(i-j+2);
}
System.out.println();
}
}
}
This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}