Cant find the error in coins array. when i tried to initialize the array with n+10 elements it worked. but actually it should be using only the n elements. where am i getting it wrong?
import java.util.Scanner;
public class MaximumContiguousSum {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int amount, n;
System.out.print("Enter number of types of coins : ");
n = in.nextInt();
int[] coins = new int[n];
System.out.print("Enter coins values : ");
for(int i=0; i<n; i++){
coins[i] = in.nextInt();
}
System.out.print("Enter the amount : ");
amount = in.nextInt();
int[] arr = new int[amount+1];
arr[1]=1; arr[0]=0;
for(int i=2; i<=amount; i++){
arr[i]=100;
int j=0;
//Error in the following line
while(coins[j]<=i && j<n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
j++;
}
}
System.out.println("The number of coins to be used : " + arr[amount]);
in.close();
}
private static int min(int a, int b) {
// TODO Auto-generated method stub
return (a<b)?a:b;
}
}
Output:
Enter number of types of coins : 3
Enter coins values : 1 2 7
Enter the amount : 10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MaximumContiguousSum.main(MaximumContiguousSum.java:22)
You have an off-by-one error. Your line:
while(coins[j]<=i && j<=n)
Will try to grab coins[n] before it quits, and the final index of your array is actually n-1
Don't check greater than or equal on the error line
change this while(coins[j]<=i && j<n){ to while(coins[j]<i && j<n){ in your code
This
int[] coins = new int[n];
declares coins to have n elements with maximum index n - 1
this
while(coins[j]<=i && j<=n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
Will attempt to access coins[n] when j = n which is past the end
Edit: arr[i-coins[j]] is protected against.
finally this:
while(coins[j]<=i && j<n)
should be this
while(j < n && coins[j]<=i)
Related
Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.
Example:
If the user wants to input 3 numbers which are 10, 8, 1
10-8-1 = 1
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t++)
{
total = number[t] - number[t+1];
}
System.out.println("total: " + total);
Change the 2nd loop to this:
total = number[0];
for (int i=1; i<number.length; i++) {
total -= number[i];
}
You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.
Remember the number of items in the array must be equal to or larger than 2.
this line is totally wrong : total = number[t] - number[t+1]; as in the last loop
total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .
so as mentioned above the full correct answer code is :
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
total = number[0];
for (int i=1; i<number.length; i++) {
total = total - number[i];
}
System.out.println("total: " + total);
}
}
and here is image of the output:
[][1]
Here is a one liner (computation wise) using streams. Take the first element, stream the array skipping the first element and subtract the sum of the remaining.
int[] arr = { 10, 8, 3, 1 };
int sum = arr[0] - IntStream.of(arr).skip(1).sum();
System.out.println(sum);
But no matter how you do it, you have the potential for int overflow or underflow depending on the size of your values and the length of the array.
This code is to input n integer values and calculate the no. of even and odd values among those inputted values.
This java code shows ArrayIndexOutOfBoundsException when used do..while loop, however when used for loop it worked fine. Haven't changed any thing just rearranged the syntax so as to convert for loop into do while loop.
FOR LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
}
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code works fine and gives suitable output.
DO...WHILE LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0, i=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code has a runtime exception i.e.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at EvenOddCount.main(EvenOddCount.java:20)
In your original code, you had two separate i variables:
for(int i=0;i<n;i++)
...
for(int i=0;i<a.length;i++)
In your do/while version, you've got one i variable. Once you've gone through the first loop, the value of i will be n - but you start on the second loop without resetting it to 0, so on the very first iteration it will be out of range.
You can fix that by adding:
i = 0;
just before the second do/while loop, but be aware that you'll still have a problem (even in the first loop) if n is 0, because you're not checking the condition until the end of the iteration. If you use:
while (i < n)
and
while (i < a.length)
instead, that will check the condition before the first iteration, so it will execute 0 times when n is 0. (You still need to reset i to 0 before the second loop though.)
U need to reset the value of i :
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
i =0;
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
I have to create a program that reads an arbitrary number of positive integers from the user and store them into an array. The number of input data is not more than 100. After the user finishes the program should remove all even integers and place them in another array leaving all odd integers in the original array with no holes. It should display the contents in the original array as the order of input, the contents of the even integer array with a count, and the contents of the original array after taking out all even integers with a count
No third array should be used
Im having trouble displaying the original array and original integer array after taking out the even integers. here is my code so far
import java.util.*;
public class Arrays
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i=0;
int nextElm=0;
int a,b;
int[] origArray = new int[100]; /* Two arrays at length 100*/
int[] evenArray = new int[100];
while((i<origArray.length && i<evenArray.length)&& nextElm!= -1)
{
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm%2 != 0)//Sorts even numbers
{
origArray[i]= nextElm;
}
else
evenArray[i] = nextElm;
i++;
}
System.out.print("\n");
System.out.println("Even Array: ");
for (b=0; b<evenArray.length;b++)
{
if (evenArray[b]== -1)
{
evenArray[b]= 0;
}
if(evenArray[b]!= 0)
{
System.out.print(evenArray[b]+" ");
}
}
System.out.print("\n");
System.out.println("Original Array: ");
for(a=0; a<origArray.length && a<evenArray.length; a++)
{
if (origArray[a]== -1)
{
origArray[a]= 0;
}
if(origArray[a]!= 0)
{
System.out.print(origArray[a]+" " + evenArray[a]);
}
}
System.out.print("\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i = 0;
int nextElm = 0;
int a, b;
int[] origArray = new int[100]; /* Two arrays at length 100 */
int[] evenArray = new int[100];
while (nextElm != -1) {
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm > 0) {
origArray[i] = nextElm;
i++;
}
}
int x = 0;
System.out.println();
// Displays original array and sorts even numbers to even array +
// original count
System.out.printf("\nTotal count of original array is : %d", i);
System.out.println();
for (int orgNumber : origArray) {
if (orgNumber != 0) {
System.out.print(orgNumber + " ");
}
if (orgNumber % 2 == 0) {
if (orgNumber != 0) {
evenArray[x] = orgNumber;
x++;
}
}
}
System.out.println();
// Displays sort even numbers to even array + even count
System.out.printf("\nTotal count of even array is : %d", x);
System.out.println();
for (int evenNumber : evenArray) {
if (evenNumber != 0) {
System.out.print(evenNumber + " ");
}
}
// Displays sort odd numbers from original array + odd count
System.out.printf("\nTotal count of orignal array without even is : %d", i - x);
System.out.println();
for (int oddNumber : origArray) {
if (oddNumber % 2 != 0) {
System.out.print(oddNumber + " ");
}
}
}
This should work perfectly if I understood your question well. Hope you find this helpful.
You want three separate loops. One for inputting the values (I would suggest the while construct as you have done) and one for sorting the values.
Your input loop should read in a new number each time and only quit when the user wants to. For example, if the user inputs a negative number, then your loop will quit. Like this:
System.out.println("Enter any number of numbers; enter a negative when finished.");
int nextElm = 0;
int count = 0;
while (nextElm >= 0) {
nextElm = scan.nextInt();
origArray[count] = nextElm;
count++;
}
// This is where you would put a print statement that prints the original array with a count.
Now after this, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array, like so:
origArray = java.util.Arrays.copyOf(origArray, count+1);
Next, use a for loop to iterate through the array, and move even numbers to the other array. This is the tricky part, because removing items from an array requires iteration to move each value to it's previous index.
int j = 0;
for (int i=0; i<count; i++){
if (origArray[i] % 2 == 0){
evenArray[j] = origArray[i]; //add even number to evenArray
j++; //move to next index of evenArray
for (int k=i; k<(origArray.length-1); k++){
origArray[k] = origArray[k+1]; //store next value in current index
}
}
}
Then finally, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array again, like so:
evenArray = java.util.Arrays.copyOf(evenArray, j+1);
Disclaimer: This was all coded from the hip so let me know if I missed something or did something incorrectly.
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());
How do I solve the following problem?
Please see link here.
My code only works when the data is entered horizontally.
How would I go about changing my code in order to be able to display the sums like my 2nd example above in the link?
Here's my code:
import java.util.Scanner;
public class sums_in_loop {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String code = scanner.nextLine();
String list[] = code.split(" ");
for( int counter = 0; counter < list.length; counter++) {
int sum = 0;
System.out.println(sum + " ");
}
}
}
Judging by the URL you provided, the solution is rather straight-forward.
Ask the user how many pairs to enter
Declare an array of integers with a size of the user input from step 1
Run a loop based on the user input from step 1
Declare an array of integers with a size of 2
Run a nested loop of two to get user input for the two integers
Add the two numbers into the array from step 2
Display results
With that in mind (I assume only valid data is being used):
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("How many pairs do you want to enter? ");
int numberOfPairs = input.nextInt();
int[] sums = new int[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
int[] numbers = new int[2];
for (int j = 0; j < numbers.length; j++) {
// Be sure to enter two numbers with a space in between
numbers[j] = input.nextInt();
}
sums[i] = numbers[0] + numbers[1];
}
System.out.println("Answers:");
for (int sum : sums) {
System.out.print(sum + " ");
}
}
Results:
How many pairs do you want to enter? 3
100 8
15 245
1945 54
Answers:
108 260 1999