Printing an array on a certain line - java

I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}

I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.

Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.

Related

Java calculate ISBN using for loop [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am still new to Java, this question like: An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer.
See my code below:
It is working but the result is not correct!
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 0 ; i < arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 0 ; j < arr.length; j++)
{
System.out.print(arr[j]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
I just want to use loop, make my method works. , i know how to use method without loop.
well. for JAVA
an array index start from 0. and Max index is length - 1.
if the index is not within this range. an arrayoutofbounds exception will be thrown
The problem is not that you are doing int i = 1 instead of int i = 0. The problem is that you changed i < arr.length; to i <= arr.length;. Since arr.length is 9, your code is trying to refer to arr[9] but arr only has elements arr[0] through arr[8].
First, review how we use arrays...
int[] I = new int[3];
The above creates an array with 3 spots in it. After instantiating the array, each element is based off of a 0-index. You only have I[0], I[1], and I[2] available (note this is three numbers) and trying to access I[3] will throw the error that you encountered in your program above: ArrayIndexOutOfBoundsException.
That being said, your loop is trying to access arr[9]. The highest index you have in the array is arr[8], because despite the array having 9 elements in it, it's 0-indexed.
Assuming you MUST have i starting from 1 for a homework assignment or something, change your code to:
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 1 ; i <= arr.length; i++)
{
arr[i-1] = input.nextInt();
checkSum = (arr[i-1] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 1 ; j <= arr.length; j++)
{
System.out.print(arr[j-1]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
int[] arr = new int[9];
This means the array has 9 slots. And the numbering of those slots starts from 0. Thus,
arr[0] is the first slot
arr[1] is the second slot
The last slot would be arr[8]. But in the following code you are iterating till i is equal to 9 which does not exist.
for (int i = 1 ; i <= arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * (i+1)) % 11;
}
This results in the ArrayIndexOutOfBoundsException. Change for (int i = 1 ; i <= arr.length; i++) to for (int i = 0 ; i < arr.length; i++)

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

Trouble printing out pattern in array

I am trying to get the number of pattern to printout from the array but under my number of pattern no pairs were printed out this is an example of what i am trying to get
(Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3)
but I do not know what to write from beyond number of patterns
The code:
public class FindIt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int Sum = 0;
int[] InsertNumbers = new int[10];
System.out.println("Sample output #1:");
System.out.print("Array: ");
for(int i = 0; i < 10; i++)
{
InsertNumbers[i]=(int)(Math.random()*10)+1;
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Array: ");
for(int i = 0; i < 5; i++)
{
ComputePattern(InsertNumbers, Sum);
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Number of patterns: ");
}
public static void ComputePattern(int[] InsertNumbers, int Sum)
{
for(int i = 0; i < 2; i++)
{
InsertNumbers[i] = Sum;
Sum = Sum + Sum;
}
}
}
It is quite hard to understand your code but here is what I can tell you.
You have managed to get to ask the user input but I feel that the following would be better.
Instead, try having two arrays, one which the user can input 10 integers, and the other array with the sum of the pairs, hence an array containing 5 integers.
With the help of a For Loop and a formula, you can use it to get the 2 consecutive values. The first formula being x*2, the second being (x*2)+1.
With x being 0 in the for loop, and loop it for 5 times.
Afterwards, you get the values of the x*2 and the (x*2)+1 in the array, and sum them together.
Then with the sum, you can then use it to calculate the count of patterns.
Suggestion : Try to be consistent with your println and print. It is quite confusing and I am not quite sure as to why you have set println for certain text and print for the rest.
No patterns were printed because you have no print statements after you print Number of patterns.

2D Array with user input and random numbers

I am trying to generate a program that ask the user a number "n" and displays a 2 x n array. E.g:
1 2 3 4 5 (User input)
5 8 2 1 5 (Random numbers)
I can't see to make my code to work. Here is my code:
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
System.out.println(A[2][n]);
System.out.print("Distance between exit i and exit j is: " + distance());
}
public static int distance(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter exit i: ");
int i = input.nextInt();
System.out.print("Please enter exit j: ");
int j = input.nextInt();
return i + j;
}
}
I am getting this error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
5"
How can I fix it?
And I think my Math.random is wrong. Can you guys help me with some advises or where am I doing things wrong?
Thanks.
All your errors lie within and after your for-loop:
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
If n = 5, A[5].length does not exist, because the first dimensions of your array only exist between 0 and 1. A[2] reserves space for 2 int primitives, the first is at index 0 and the last is at index 1. Even if that is changed, the i variable your for loop declares is incremented beyond 1 and so the JVM will throw a ArrayIndexOutOfBoundsException.
When declaring an array with the dimensions [2][n], (given n is an Integer, which will be provided by the user via the scanner) you cannot access arrayReference[2][x]
Arrays are based on a 0 index structure...
Consider the following:
int [][] A = new int[2][2];
You can only access A[0][0], A[0][1], A[1][0] & A[1][1].
you CANNOT access A[2][0], A[2][1] or A[2][2].
Here's what you need to do:
//A.length will give you the length of the first dimension (2)
for(int i=0; i<A.length; i++){
for(int j=0; j<n; j++){
A[i][j] = (int) (Math.random()*10);
}
}
}
System.out.println(A[1][n-1]);
System.out.print("Distance between exit i and exit j is: " + distance());

Finding repeats in a 2D array

I have made a program that outputs the number of repeats in a 2D array. The problem is that it outputs the same number twice.
For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28.
The output I get is:
Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9 repeats 2 times.
Number 1 repeats 1 times.
Number 28 repeats 2 times.
I want it so it skips the number if it has already found the number of repeats for it. The output should be:
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1 repeats 1 times.
Here is my code:
import java.util.Scanner;
public class Repeat
{
static Scanner leopard = new Scanner(System.in);
public static void main(String [] args)
{
final int ROW = 10; //Row size
final int COL = 10; //Column size
int [][] num = new int[ROW][COL];
int size;
//Get input
size = getData(num);
//Find repeat
findRepeats(num, size);
}
public static int getData(int [][] num)
{
int input = 0, actualSize = 0; //Hold input and actualSize of array
System.out.print("Enter positive integers (-999 to stop): ");
//Ask for input
for(int i = 0; i < num.length && input != -999; i++)
{
for(int j = 0; j < num[i].length && input != -999; j++)
{
input = leopard.nextInt();
//Check if end
if(input != -999)
{
num[i][j] = input;
actualSize++;
}
}
}
System.out.println();
return actualSize;
}
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 0, row = 0, col = 0;
for(int x = 0; x < size; x++)
{
//Set to number
findNum = num[row][col];
//Loop through whole array to find repeats
for(int i = 0; i < num.length; i++)
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] == findNum)
total++;
}
}
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 0;
}
}
}
I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. I cannot use any classes or code that is not used in the code.
Since you cannot use anything other than this, lets say, basic elements of Java consider this:
Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). On the start of the algorithm the new arrays are empty.
When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. If it is, just increment the value (count) in the second temporary array for one (+1). If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically).
This way you are building pairs of numbers in two arrays. The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first.
At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment.
It's counting the number two times, first time it appears in the code and second time when it appears in the code.
To avoid that keep a system to check if you have already checked for that number. I see you use check int array but you haven't used it anywhere in the code.
Do this,
Put the number in the check list if you have already found the count of it.
int count = 0;
check[count] = findNum;
count++;
Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input.
Next time in your for loop skip checking that number which you have already found a count for
for(int x = 0; x < size; x++) {
findNum = num[row][col];
if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
//skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
}
}
Frankly speaking I think you have just started to learn coding. Good luck! with that but this code can be improved a lot better. A piece of advice never create a situation where you have to use 3 nested for loops.
I hope that you understood my solution and you know how to do it.
All answers gives you some insight about the problem. I try to stick to your code, and add a little trick of swap. With this code you don't need to check if the number is already outputted or not. I appreciate your comments, structured approach of coding, and ask a question as clear as possible.
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 1, row = 0, col = 0;
int [] check = new int[size];
while(row < num.length && col < num[0].length)
{
//Set to number
findNum = num[row][col];
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Loop through whole array to find repeats
for(int i = row; i < num.length; i++)
{
for(int j = col; j < num[i].length; j++)
{
if(num[i][j] == findNum) {
total++;
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
if(row < num.length - 1 && col < num[0].length -1)
num[i][j] = num[row][col];
}
}
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 1;
}
}
you can use a HashMap to store the result. It Goes like this:
// Create a hash map
HashMap arrayRepeat = new HashMap();
// Put elements to the map
arrayRepeat.put(Number, Repeated);

Categories