Electronics Shop - java

I have been working on this question, and after submitting my code 7 cases passed, however, 9 cases failed. The question link is here of HackerRank : Electronic Shop
Problem Statement
A girl wants to buy a keyboard, and a USB drive, she want to spend as much as possible but within budget (combining both the items). And if the price of both the items exceeds her budget, return -1 or she can't buy. What is mandatory is that She wants to buy both the items, not a single one.
Example
A range of keyboards is given in the form of an array [40, 50, 60], and USB drives is given as [5,8,12]. Her max budget is 60. Now if we sum up both the things we get two max value of combination :
40 + 12 = 52
50 + 8 = 58
Since 58 one is greater, hence she will get the items worth of 50 and 8.
Input format
The first line contains three space-separated integers b, n, and m, her budget, the number of keyboard models and the number of USB drive models.
The second line contains space-separated integers , the prices of each keyboard model.
The third line contains space-separated integers , the prices of the USB drives.
Output Format
Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
My Algo
1. Take answer variable as 0, and max value initialize it with first element of keyboard + first element of usb drives
2. loop through keyboard, make an inner loop for usb
3. Compare keyboard[i] + drives[j], if greater than b, then return -1.
4. Else find the max value and assign it to answer
5. return answer
My logic is as simple as the requirements, but somehow fails for the cases which has a very large number of elements in the array.
Code
static int getMoneySpent(int[] keyboards, int[] drives, int b) {
int answer = 0, maxAmount = keyboards[0] + drives[0];
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
// Ofcourse if all i+j values will be greater than the max budget then -1
if((i+j) > b)
answer = -1;
else if((i+j) == b){
answer = i+j;
}else{
/*If the value is smaller than the max budget, the finding the max value we get after adding them and comparing with the maxAmount variable */
if((i+j) > maxAmount){
maxAmount = i+j;
answer = maxAmount;
}
}
}
}
return answer;
}
I'm having two cases which failed,, here they are :
Failed Test Case 1
Input =>
539855 818 628
380710 674456 878173 532602 868253 721585 806107 141310 790209 212031
304748 818920 80938 322601 403071 22899 173564 153826 695108 223665
346178 957539 975830 573171 641117 932941 822666 575293 132555 479463
862209 313799 922966 606508 487172 139230 606390 898464 764983 829520
174879 317603 502680 953013 398753 825387 146407 666457 367618 121790
68188 478342 25818 506222 135197 232604 963333 79984 549654 776899
966040 122063 432596 594425 311887 936661 506256 876303 439611 277816
105689 851641 640971 333 216087 17692 619728 602689 650348 364881
152060 386548 61364 564569 780938 191826 459905 211804 58177 484711
995091 754424 57794 619638 695192 297423 983901 430435 239234 170704
142282 74647 121413 782873 303344 265448 101069 177807 692318 691774
62306 618191 509537 633333 996922 228947 814154 232698 615359 220853
306323 173792 624037 655872 527161 848207 426180 724481 130740 792273
886804 404890 449886 654224 194667 354317 367843 525624 414224 481744
827725 176927 733780 387166 769479 964040 1{-truncated-}
Expected Output
539854
For full input data here is the link : Input Array Data Full
Failed Test Case 2
Input =>
374625 797 951
183477 732159 779867 598794 596985 156054 445934 156030 99998 58097
459353 866372 333784 601251 142899 708233 651036 20590 56425 970129
722162 832631 938765 212387 779 181866 992436 183446 617621 304311
611791 524875 7068 432043 23068 291295 524893 611991 399952 139526
46677 292211 973975 366445 232824 456173 90627 785353 618526 199719
382549 514351 983453 592549 466869 46461 860135 607682 680461 170563
450601 65067 13268 949100 942415 965850 563416 808580 385504 304683
15970 97695 230946 684388 241080 440252 683418 122066 610135 495289
833383 34397 173404 909526 391149 258839 182278 662672 755532 311782
425252 520186 207989 546834 567829 184897 31321 969804 842475 775308
449856 939711 395240 895029 926868 598035 727436 922082 326615 88513
570573 196028 520952 45238 961389 325404 844725 388765 747489 271411
539814 828925 586884 356834 965473 280998 607171 542819 276062 140956
296341 802378 165305 74568 15640 987110 423497 772419 394971 198761
293555 5524 14083 815646 198888 707017 711503 729172{-truncated-}
Expected Output
374625
For full input array data for this one follow this link : Failed Test Case 2 Full Input
I'm there almost but somehow I'm confused why my code is not working for long input array elements. Any help would be appreciated, as it will make me learn new thing in my future endeavor.

You misunderstood the question. Answer should be -1 if you can't buy any keyborad+usb. Not if there is one set unaffordable, but if they all are. With your current code, what would it return if the very last set is unaffordable?
Here is a code that should work. And comments to explain:
int answer = -1; // that's the default answer.
int maxAmount = 0; // what if first keyboard + first usb are unaffordable? let's put it to 0
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
if((i+j) > b) {
// do nothing, it's unaffordable (and remove this block)
}else if((i+j) == b){
answer = i+j;
return answer;// it can't be more, stop the loop and return the solution
} else if((i+j) > maxAmount){ // no need to put an else, then an if both conditions are related
maxAmount = i+j;
answer = maxAmount;
}
}
}
Of course, if you remove the first empty ifblock from the above code, you will have to change the last condition in order to check if it's below the max allowed:
if((i+j)>maxAmount && (i+j)<=b)

int getMoneySpent(int keyboards_count, int* keyboards, int drives_count, int* drives, int b) {
int price=-1;
for(int i=0;i<drives_count;i++)
{
for(int j=0;j<keyboards_count;j++)
{
if((drives[i]+keyboards[j]>price) && (drives[i]+keyboards[j]<=b))
{
price=drives[i]+keyboards[j];
}
}
}
return price;
}

Javascript Solution:
function getMoneySpent(keyboards, drives, b) {
const combos = [];
let maxCost = 0
keyboards.forEach(keyboard => {
drives.forEach(drive => {
let currentComboCost = keyboard+drive;
maxCost = ((currentComboCost <= b) && (currentComboCost > maxCost)) ? currentComboCost : maxCost;
})
})
return maxCost || -1;
}

Related

java maximum value of string after split

I'm taking beginner's java course and I have this kind of task:
User inputs word + number, for example, "animal" + "age":
horse:3
dog:5
parrot:2
cat:7
I have to make the program to print out the age of the oldest animal.
For example like this:
The age of the oldest animal is: 7
Now, this is what I have written so far. My problem is that I don't know how to make the program compare the numbers...
while (true) {
String luettu = x.nextLine(); // user inputs animals and numbers
if (dataIn.equals("")) { // when inputs nothing program stops
break;
}
// Here I separate the animal and number with star symbol
String[] separatedData = dataIn.split(":");
// From now on, I'm supposed to focus on the numbers, create the rule for how to find the highest value
x = x Integer.valueOf(separatedData[1]); // Must target the values in the index 1 (the numbers) but how?
}
int maxNumber = separatedData.lenght;
int i = 0;
// I don't know how to loop and compare the numbers... and I thin "while" doesn't make sense here
while ( i < size of separatedData) {
if(maxNumber < separatedData) {
maxNumber = separatedData;
}
System.out.println("The age of the oldest animal is: " + maxNumber); // printing the result
So half of the code is a mess and I'm stuck.
Please help me and if you can give explanations, that would be great, thanks! :)
When finding the maximum of something, set the max to the smallest value possible. That would be
maxAge = Integer.MIN_VALUE
Then set a string variable like this.
String oldestAnimal = "";
Now as you loop thru the values, compare the current age to max. If age is larger, set
max to age and set oldestAnimal to the animal associated with that age.
The compare would be like:
if (age > max) {
// set appropriate values.
}
When you are done, you will have the results.

Counting Apple and Oranges

I have seen that this question has been asked earlier, this is the link : Apple and Orange HackerRank. I must tell you that my doubt is not like this person, it is just that I've written a code which works fine on for most of the test cases, and fails for some either.
I have checked my code, and I'm fairly confident that my code is something which is working fine.
The question link is : Apple And Orange HackerRank Question
Problem Statement
Given a person house whose house length is between variables s and t, and we have two trees, one is apple other one is orange. Since we have been given some distance of the fallen apple, and oranges respectively, what we have to do is to find those apples, and oranges whose distance falls in between the s and t, or I must say which falls on xyz person's house.
Input Format
The first line contains two space-separated integers denoting the respective values of s and t.
The second line contains two space-separated integers denoting the respective values of a and b.
The third line contains two space-separated integers denoting the respective values of m and n.
The fourth line contains space-separated integers denoting the respective distances that each apple falls from point a.
The fifth line contains space-separated integers denoting the respective distances that each orange falls from point b.
Code
static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
int appleSum=0, orangeSum=0, appleCount=0, orangeCount=0;
for(int i : apples){
appleSum = Math.abs(a+i);
if(appleSum>=s && appleSum<=t)
appleCount++;
}
for(int j : oranges){
orangeSum = Math.abs(b+j);
if(orangeSum>=s && orangeSum<=t)
orangeCount++;
}
System.out.print(appleCount + "\n" + orangeCount);
}
This is my piece of code which works fine on most of the test cases, but this case actually confused to hell. I'm actually writing down the gist of one of the failed test cases, and will give you the link for the same if it works out well for you guys.
Passed Test Case {1}
7 11
5 15
3 2
-2 2 1
5 -6
Passed Test Case {2}
7 10
4 12
3 3
2 3 -4
3 -2 -4
Failed Test Case
37455 87275
35609 89610
73201 77971
19736 19374 -68796 0 -68800 -80005 -88383 -8147 73241 -33256 20227 0
41620 30182 -95883 -88718 93989 44405 66495 87717 100000 -99845 -63634
98450 -63318 23501 -39150 22335 4955 -98587 -13608 -95388 -41752 4959
22375 -20025 -72101 -90667 -41569 94758 -26725 -53444 -8783 -81879
57041 23682 -60064 -23505 2850 96653 18487 -6644 -90710 71994 21513
36066 -65894 -9897 -86990 -97347 89784 88447 93133 12662 61685 -22914
-39075 -96807 -80465 -53820 36851 -51794 -11967 36658 -75592 22004 -961
66645 -93123 -65326 81871 -21785 -48242 -63552 32509 51078 -37656
-14966 4017 -58411 9346 13544 -63028 -93738 93924 68463 55032 -10046
87907 -20967 78972 85338 19584 45460 84382 -34690 -82301 14093 -60802
4170 -90955 92241 -34932 68913 -22262 49469 -45729 7942 65753 17354
-28647 93058 -43811 21411 8543 -44799 -71815 -40743 60445 -66946 -85090
-96873 97385 -15317 54454 -21021 -60256 -41301 -98896 -97184 63098
-60230 41376 42273 45807 58041 54260 21196 -85191 85267 -28305 30220
-76826 82999 72627 7{-truncated-}
Expected Output
89610
19582
There are more to this and the link is here : Test Case Inputs
PLEASE NOTE : I have not asked for the solution actually, my code works but I don't know why this logic fails for the inputs like this.
Any help would be appreciated! Thanks :)
EDITS
I have tried using the long in place of int, in case for the larger value like the one which is there in the failed test case, but again it got failed!
long appleSum=0, orangeSum=0, appleCount=0, orangeCount=0;
This code passed all test cases, what went wrong for you is you are using Math.abs(),you shouldn't do that because there can be negative values of sum as well.
static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
int appleCount = 0;
int orangeCount = 0;
for(int i:apples){
if(s<=i+a && i+a<=t)
appleCount++;
}
for (int j : oranges) {
if (s <= j + b && j+b <= t)
orangeCount++;
}
System.out.println(appleCount);
System.out.println(orangeCount);
}
JavaScript code for countAppleAndOranges function of hacker rank
let applesCount=0, orangesCount=0;
for(let x=0; x<apples.length; x++){
apples[x]=apples[x]+a;
if((apples[x]>=s)&&(apples[x]<=t)){
applesCount++
}
}
for(let x=0; x<oranges.length; x++){
oranges[x]=oranges[x]+b;
if((oranges[x]>=s)&&(oranges[x]<=t)){
orangesCount++;
}
}
console.log(applesCount);
console.log(orangesCount);
The question is too old, but still there may be people who might need this.
abs() is the mistake you made.
See the code
void countApplesAndOranges(int s, int t, int a, int b, vector<int> apples, vector<int> oranges) {
int size_a=apples.size();
int size_o=oranges.size();
int count_a=0,count_o=0;
for(int i=0;i<size_a;i++)
{
if(apples[i]+a>=s&&apples[i]+a<=t)
{
count_a++;
}
}
for(int j=0;j<size_o;j++)
{
if(oranges[j]+b<=t&&oranges[j]+b>=s)
{
count_o++;
}
}
cout<<count_a<<'\n'<<count_o;
}

Find Survivor when n people are sitting in a circle

Hi I am across this problem and trying to solve this
Take a second to imagine that you are in a room with 100 chairs arranged in a circle. These chairs are numbered sequentially from One to One Hundred.
At some point in time, the person in chair #1 will be told to leave the room. The person in chair #2 will be skipped, and the person in chair #3 will be told to leave. Next to go is person in chair #6. In other words, 1 person will be skipped initially, and then 2, 3, 4.. and so on. This pattern of skipping will keep going around the circle until there is only one person remaining.. the survivor. Note that the chair is removed when the person leaves the room.Write a program to figure out which chair the survivor is sitting in.
I made good progress but stuck with a issue, after the count reaches 100 and not sure how to iterate from here, can any one help me, this is my code
import java.util.ArrayList;
public class FindSurvivor {
public static void main(String[] args) {
System.out.println(getSurvivorNumber(10));
}
private static int getSurvivorNumber(int numChairs) {
// Handle bad input
if (numChairs < 1) {
return -1;
}
// Populate chair array list
ArrayList<Integer> chairs = new ArrayList<Integer>();
for (int i = 0; i < numChairs; i++) {
chairs.add(i + 1);
}
int chairIndex = 0;
int lr =0;
while (chairs.size() > 1) {
chairs.remove(lr);
chairIndex+=1;
System.out.println(lr+" lr, size "+chairs.size()+" index "+chairIndex);
if(lr==chairs.size()||lr==chairs.size()-1)
lr=0;
lr = lr+chairIndex;
printChair(chairs);
System.out.println();
}
return chairs.get(0);
}
public static void printChair(ArrayList<Integer> chairs){
for(int i : chairs){
System.out.print(i);
}
}
}
The answer is 31. Here are three different implementations
var lastSurvivor = function(skip, count, chairs) {
//base case checks to see if there is a lone survivor
if (chairs.length === 1)
return chairs[0];
//remove chairs when they are left/become dead
chairs.splice(skip, 1);
//increment the skip count so we know which chair
//to leave next.
skip = (skip + 1 + count) % chairs.length;
count++;
//recursive call
return lastSurvivor(skip, count, chairs);
};
/** TESTS *******************************************************************
----------------------------------------------------------------------------*/
var result = lastSurvivor(0, 0, chairs);
console.log('The lone survivor is located in chair #', result);
// The lone survivor is located in chair # 31
/** ALTERNATE IMPLEMENTATIONS ***********************************************
-----------------------------------------------------------------------------
/* Implemenation 2
-----------------*/
var lastSurvivor2 = function(chairs, skip) {
skip++;
if (chairs === 1)
return 1;
else
return ((lastSurvivor2(chairs - 1, skip) + skip - 1) % chairs) + 1;
};
/** Tests 2 *******************************************************************/
var result = lastSurvivor2(100, 0);
console.log('The lone survivor is located in chair #', result);
// The lone survivor is located in chair # 31
/* Implemenation 3
------------------*/
var chairs2 = [];
for (var i = 1; i <= 100; i++)
chairs2.push(i);
var lastSurvivor3 = function(chairs, skip) {
var count = 0;
while (chairs.length > 1) {
chairs.splice(skip, 1);
skip = (skip + 1 + count) % chairs.length;
count++;
}
return chairs[0];
};
/** Tests 3 *******************************************************************/
var result = lastSurvivor3(chairs2, 0);
console.log('The lone survivor is located in chair #', result);
// The lone survivor is located in chair # 31
I'm not sure what your removal pattern is but I'd probably implement this as a circular linked list where the 100th seat holder will connect back to the 1st seat holder. If you use an array, you will have to worry about re-organizing the seats after every removal.
There is elegant analytical solution:
Let's change numbering of people: #2 -> #1, #3 -> #2, ..., #1 -> #100 (in the end we just need to substract 1 to "fix" the result). Now first person remains instead or leaving. Suppose that there is only 64 people in circle. It's easy to see that after first elimination pass 32 people in circle will remain and numbering will start again from #1. So in the end only #1 will remain.
We have 100 people. After 36 people will leave the circle we will end up with 64 people - and we know how to solve this. For each person that leaves the room one person remains, so circle with 64 people will start from 1 + 2*36 = #73 (new #1). Because of changing indexes on first step final answer will be #72.
In general case res = 2*(N - closest_smaller_pow_2) = 2*N - closest_larger_pow_2. The code is trivial:
public static long remaining(long total) {
long pow2 = 1;
while (pow2 < total) {
pow2 *= 2;
}
return 2*total - pow2;
}
Also this algorithm has O(log(N)) complexity instead of O(N), so it's possible to calculate function for huge inputs (it can be easily adapted to use BigInteger instead of long).
First, let's assume the chairs are numbered from 0. We'll switch the numbering back at the end -- but usually things are simpler when items are enumerated from 0 rather than 1.
Now, if you've got n people and you start eliminating at chair x (x is 0 or 1) then in a single pass through you're going to eliminate half the people. Then you've got a problem of roughly half the size (possibly plus one), and if you solve that, you can construct the solution to the original problem by multiplying that sub-result by 2 and maybe adding one.
To code this, it's simply a matter of getting the 4 cases (n odd or even vs x 0 or 1) right. Here's a version that gets the 4 cases right by using bitwise trickery.
public static long j2(long n, long x) {
if (n == 1) return 0;
return j2(n/2 + (n&x), (n&1)^x) + 1-x;
}
A solution with chairs numbered from 1 and without the extra argument can now be written:
public static long remaining(long n) {
return 1 + j2(n, 0);
}
This runs in O(log n) time and uses O(log n) memory.
If your step is incremental you can you use the following code:
int cur = 0;
int step = 1;
while (chairs.size() > 1) {
chairs.remove(cur);
cur += ++step;
cur %= chairs.size();
}
return chairs.get(0);
If your step is fixed to 1 then based on explanation provided by #Jarlax you can solve the problem with one-line of code in O(log n) time:
//for long values
public static long remaining(long numChairs) {
return (numChairs << 1) - (long)Math.pow(2,Long.SIZE - Long.numberOfLeadingZeros(numChairs));
}
//for BigInteger values
public static BigInteger remaining(BigInteger numChairs) {
return numChairs.shiftLeft(1).subtract(new BigInteger("2").pow(numChairs.bitLength()));
}
However, if you stick with ArrayLists no extra variables are required to your code. Always remove the first element and remove-then-add the next at the end of the list. This is however O(n).
while (chairs.size() > 1) {
chairs.remove(0);
chairs.add(chairs.remove(0));
}
return chairs.get(0);

The correct Recursive backtracking algorithm?

My assignment is to find a way to display all possible ways of giving back change for a predetermined value, the values being scanned in from a txt file. This must be accomplished by Recursive Backtracking otherwise my solution will not be given credit. I will be honest in saying I am completely lost on how to code in the appropriate algorithm. All I know is that the algorithm works something like this:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
The issue is I haven't the slightest clue on how or where to begin, only that that has to be accomplished, or if any other solutions are apparent.
This is my code thus far:
UPDATED
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
Here is the input file that I scan in
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
OUTPUT
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
So using the numbers in my coinTypes ArrayList, I need a generic code algorithm to show all possible ways of receiving, for example, 143 ($1.43) back in change using the coins in the file with all pennies being the last way to show it.
Please do not think I want you to write me the algorithm, I am simply wanting help writing one otherwise I will learn nothing. Thank you all for any answers or help you can give it means a lot to me! Please let me know if i missed anything or you need more info
The example that you walk through seems to be mostly correct. The only error is this: again discarding a dime and nickel, which should be again discarding a *penny* and nickel (but I think that's just a typo.)
To write a recursive backtracking algorithm, it is useful to think of the recursive call as solving a subproblem of the original problem. In one possible implementation of the solution, the pseudocode looks like this:
/**
* findChange returns true if it is possible to make *change* cents of change
* using the coins in coinTypes. It adds the solution to answerCoins.
* If it's impossible to make this amount of change, then it returns false.
*/
boolean findChange(int change, List<Integer> coinTypes, List<Integer> answerCoins) {
if change is exactly 0: then we're done making change for 0 cents! return true
if change is negative: we cannot make change for negative cents; return false
otherwise, for each coin in coinTypes {
// we solve the subproblem of finding change for (change - coin) cents
// using the recursive call.
if we can findChange(change - coin, coinTypes, answerCoins) {
// then we have a solution to the subproblem of
// making (change - coins) cents of change, so:
- we add coin to answerCoins, the list of coins that we have used
- we return true // because this is a solution for the original problem
}
}
//if we get to the next line, then we can't find change for any of our subproblems
return false
}
We would call this method with:
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer); // your desired output.
}
else {
System.out.println("Can't find change!");
}

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Categories