Java calculate ISBN using for loop [duplicate] - java

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++)

Related

How to fill array with random numbers limited to 0-20 [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am having trouble placing the random generator in the array, how can I get #20 random numbers from 0-9 in the array? Then you count the occurrences of those numbers.
import java.util.Random;
public class CountDigits {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int [20];
int Digits[] = {0,1,2,3,4,5,6,7,8,9};
int Count [] = new int [10];
for ( int i = 0; i < Digits.length; i++) {
for( int j = 0; j < Random.length; j++) {
if ( Digits [i] == Random [j] )
Count[i]++;
}
}
for ( int i = 0; i < Count.length; i++) {
if ( Count[i] == 1)
System.out.printf(" %d occurs 1 time " , Digits[i] );
else
System.out.printf("%d occurs %d times" , Digits[i], Count[i]);
}
result so far::
0 occurs 20 times1 occurs 0 times2 occurs 0 times3 occurs 0 times4 occurs 0 times5 occurs 0 times6 occurs 0 times7 occurs 0 times8 occurs 0 times9 occurs 0 times
You need to actually get a Random number, and get within the range. The Java Random will provide the necessary capability, and includes a .nextInt(int bound) that returns between 0 and bound:
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So something like:
Random rnd = new Random();
int num = rnd.nextInt(10); // returns between 0 and 9
Given that, you have two other questions:
- Generating 20 numbers
- Counting
Knowing that the number of possible entries is between 0 and 9, it is easy to use an array to hold the counts.
int[] counts = new int[10]; // holds between 0 and 9
for (int i = 0; i < 20; ++i) {
int num = rnd.nextInt(10);
counts[num]++;
}
The output of the counts array will give the count of the number of times a given number between 0 and 9 was randomly generated.
See an example here
You forgot to assign random numbers to the array elements.this answer to see how random numbers are generated.
You need to call Random object's nextInt(an integer) method. If you give 25 to it, it will return a random integer between 0-24 inclusive.
Example Usage:
Random rand = new Random();
int random_int = rand.nextInt(50); // --------> Random integer 0-49
And the full code:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int[20];
for (int x=0;x<20;x++) {
Random[x] = digit.nextInt(10);
}
int Digits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int Count[] = new int[10];
for (int i = 0; i < Digits.length; i++) {
for (int j = 0; j < Random.length; j++) {
if (Digits[i] == Random[j])
Count[i]++;
}
}
for (int i = 0; i < Count.length; i++) {
if (Count[i] == 1)
System.out.printf(" %d occurs 1 time ", Digits[i]);
else
System.out.printf("%d occurs %d times", Digits[i], Count[i]);
}
}
}
Outputs :
0 occurs 2 times1 occurs 2 times 2 occurs 1 time 3 occurs 3 times4 occurs 6 times 5 occurs 1 time 6 occurs 2 times7 occurs 0 times 8 occurs 1 time 9 occurs 2 times
You can print the random numbers like this
for (int x=0;x<20;x++) {
System.out.println(Random[x]);
}
You can try this:
Create an array of int with length 20, then use a simple for loop where you are gonna generate a random number and them put it inside the array
int[] random = new int[20];
for(int i=0;i<20;i++){
int r = Math.floor(Math.random()*9+1);
random[i]=r;
}

ArrayIndexOutOfBoundException when entering > 5 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
it works properly but when i enter value which is more then 5 it gives exception but not giving me output. If i enter 12 then output should be like this ( 4 , 5 , 1 , 2 , 3)
public static void main(String args[]) {
int[] a = { 1 , 2 , 3 , 4 , 5 };
int[] b = new int[5];
int j = 0,m = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter n:");
int n = sc.nextInt();
sc.nextLine();
m = n;
for(int i = n ; i < 5 ; i++) {
b[j] = a[i] - n;
System.out.println("" +b[j]);
j++;
}
for(int i = 0 ; i < n ; i++) {
b[j] = a[i] - a[i];
j++;
}
for(int k = 0 ; k < 5 ; k++) {
System.out.println("a["+k+"]:" +b[k]);
}
As suggested in the comments on your question, the issue is to do with trying to access an element in an array that is not present.
E.g.
int[] array = new int[5];
int boom = array[10]; // Throws the exception
(copied from What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?)
In your example, the problem occurs in the code here:
for(int i = 0 ; i < n ; i++) {
b[j] = a[i] - a[i];
j++;
}
The reason is that you set n to the integer that you pass in (in your example '12') and then loop over i, increasing it each time, while it is less than n.
So using an input of '12', this loop will repeat 12 times with i increasing in value from 0 to 11.
Inside the loop you then try to access the ith element in the a array; which only has 5 elements.
This is fine for the first 5 iterations of the loop (i == 0 ... i == 4), but on the 6th (i == 5) it will try to access an element in the array that is not present; hence the ArrayIndexOutOfBoundException
Hope that makes sense
(Also, note: in the future it's generally a good idea to include a stack trace along with an exception)

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] + " ");
}
}
}

finding longest sequence of consecutive numbers

Problem H (Longest Natural Successors):
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors.
Example:
Input 7 2 3 5 6 7 9 10 Output 3 this is my code so far and i have no idea why it does not work
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] array = new int[x];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
System.out.println(array(array));
}
public static int array(int[] array) {
int count = 0, temp = 0;
for (int i = 0; i < array.length; i++) {
count = 0;
for (int j = i, k = i + 1; j < array.length - 1; j++, k++) {
if (Math.abs(array[j] - array[k]) == 1) {
count++;
} else {
if (temp <= count) {
temp = count;
}
break;
}
}
}
return temp + 1;
}
}
Why two loops? What about
public static int array(final int[] array) {
int lastNo = -100;
int maxConsecutiveNumbers = 0;
int currentConsecutiveNumbers = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == lastNo + 1) {
currentConsecutiveNumbers++;
maxConsecutiveNumbers = Math.max(maxConsecutiveNumbers,
currentConsecutiveNumbers);
} else {
currentConsecutiveNumbers = 1;
}
lastNo = array[i];
}
return Math.max(maxConsecutiveNumbers, currentConsecutiveNumbers);
}
This seems to work:
public static int longestConsecutive(int[] array) {
int longest = 0;
// For each possible start
for (int i = 0; i < array.length; i++) {
// Count consecutive.
for (int j = i + 1; j < array.length; j++) {
// This one consecutive to last?
if (Math.abs(array[j] - array[j - 1]) == 1) {
// Is it longer?
if (j - i > longest) {
// Yup! Remember it.
longest = j - i;
}
} else {
// Start again.
break;
}
}
}
return longest + 1;
}
public void test() {
int[] a = new int[]{7, 2, 3, 5, 6, 7, 9, 10};
System.out.println("Longest: " + Arrays.toString(a) + "=" + longestConsecutive(a));
}
prints
Longest: [7, 2, 3, 5, 6, 7, 9, 10]=3
Since your question has "Problem H" associated with it, I'm assuming you are just learning. Simpler is always better, so it usually pays to break it down into "what has to be done" before starting on a particular road by writing code that approaches the problem with "how can this be done."
In this case, you may be over-complicating things with arrays. A number is a natural successor if it is one greater than the previous number. If this is true, increment the count of the current sequence. If not, we're starting a new sequence. If the current sequence length is greater than the maximum sequence length we've seen, set the max sequence length to the current sequence length. No arrays needed - you only need to compare two numbers (current and last numbers read).
For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int maxSequenceLen = 0; // longest sequence ever
int curSequenceLen = 0; // when starting new sequence, reset to 1 (count the reset #)
int last = 0;
for(int i = 0; i < N; i++) {
int cur = scan.nextInt();
if ((last+1) == cur){
++curSequenceLen;
}
else{
curSequenceLen = 1;
}
if (curSequenceLen > maxSequenceLen){
maxSequenceLen = curSequenceLen;
}
last = cur;
}
System.out.println(maxSequenceLen);
Caveat: I'm answering this on a computer that does not have my Java development environment on it, so the code is untested.
I'm not sure I understand this question correctly. The answer's written here assumes that the the natural successors occur contiguously. But if this is not the same then the solution here might not give the correct answer.
Suppose instead of [7 2 3 5 6 7 9 10] the input was [7 2 6 3 7 5 6 9 10] then the answer becomes 2 while the natural successor [5 6 7] is present in the array.
If the input is not sorted we'll have to use a different approach. Like using HashSet
Load the entire array into a HashSet which removes duplicates.
Pick the first value from the HashSet and assigned it to start and end and remove it from the set.
Now decrements start and check if it is present in the HashSet and continue till a particular value for start is not present int the HashSetwhile removing the value being searched from the set.
Do the same for end except that you will have to increase the value of end for each iteration.
We now have to continuous range from start to end present in the set and whose range is current_Max = end - start + 1
In each iteration we keep track of this current_Max to arrive at the longest natural successor for the entire array.
And since HashSet supports Add, Remove, Update in O(1) time. This algorithm will run in O(n) time, where n is the length of the input array.
The code for this approach in C# can be found here

Printing an array on a certain line

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.

Categories