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;
Related
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;
}
class LargestPrimeFactor{
public static void main(String args[]){
long p=0L;
long n=600851475143L;
for(long i=2L;i<(n/2);i++){
if((BigInteger.valueOf(i)).isProbablePrime(1)){
if(n%i==0){
p=i;
}
}
}
System.out.println(p);
}
}
It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?
It is working (just add a print method inside the loop to check i for example).
You are currently using the Brute-Force method:
http://www.mathblog.dk/project-euler-problem-3/
If you visit the link the guy tells you an alternative solution for it.
The problem I see without having much knowledge about this is
that the operations you currently do are way too many.
You got the value "600851475143" stored in a long datatype and you try to
reach the half (300425737571,5) using the int i (counter in your for-loop).
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE
This tells us: "A constant holding the maximum value an int can have,
2^(31)-1." = 2147483647
This is just 0,00715 (0,7%) of what you actually need.
So this leads us to an "Overflow".
Think of using the alternative method (first link)
and change the counter of your for-loop to type "long".
int maximum value is 2147483647 which is smaller than 600851475143/2
when index i reaches max value it will wrap around and start with negative number (-2147483648)
you should make your index i a long value
You have an infinite loop on the second for iteration you can only see it when you add logging before the end of the loop. It's not because it's not printing the value, when you stare at the console the iterator is still circling through 6857.
Try running the code with extra logging below.
public static void main(String args[]) {
int p = 0;
long n = 600851475143L;
for (int i = 2; i < (n / 2); i++) {
if ((BigInteger.valueOf(i)).isProbablePrime(1)) {
if (BigInteger.valueOf(n % i).compareTo(BigInteger.valueOf(0)) == 0) {
p = i;
System.out.println("Check == true Iteration"+p);
}
System.err.println("Second iterator"+p);
}
}
System.out.println("Final Value of P: "+p);
}
EDITED
The int data type can store values upto 2,147,483,647. To store numbers beyond that, use long.
long n = 600851475143L;
Not 600851475143 L, as that one space before L causes the system to not register it.
Also, int i in the for loop should be long i.
Have an assignment I cant figure out. The assignment is:
With a given method:
static void writeTexts(String text, int amount);
Print out the text in the parameter text as many times as given by the variable amount. Every print of text on separate line.
Print an empty line for every third time text is printed.
Write a main method with one or more calls of writeTexts with appropriate test data (don't know what this means) to check that the method works in all cases.
I'm a beginner and find this very difficult, have been reading and watching tutorials, also searched and found a similar question, but can`t seem to grasp this. Any help is appreciated.
The error I get when running my code is:
cannot find symbol.
What I got so far:
public class Task {
static void writeTexts(String text, int amount) {
amount = 0;
text = "hallo";
while (amount< 3) {
System.out.println(text);
amount++;
}
}
public static void main(String[] args) {
writeTexts(text);
}
}
static void writeTexts(String text, int amount) {
for(int i = 0; i < amount; i++){
//Check if the line is the a multiple of 3
//then print an empty line
//I use i + 1 because I start at 0 which is a multiple of 3
//but we are not interested by the that
if( (i + 1) % 3 == 0 ){
System.out.println("");
}
//Print the text
System.out.println(text);
}
Now for calls of writeTexts with appropriate test data that essentially means call the function with so the appropriate parameters e.g: writeText("Halo 3", 3).
I would strongly recommend you to read some more on function to get better grasp of how they work.
You are overwriting amount with 0 and you are overwriting text with "hallo" which is incorrect because you will be printing "hallo" instead of text and you lose track of how many time you need to print.
amount = 0;
text = "hallo";
Your loop will always only iterate 3 times. Instead you should iterate amount times. To do this, you will also need a counter i
int i = 0;
while (i < amount) {
You are not printing an empty line every third time text is printed. You should add this:
i++;
if (amount % 3 == 0) { // If amount is divisible by 3
System.out.println();
}
package helloworld;
public class windspeed {
public static void main(String args[]) {
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
double x = Math.pow(v, 0.16); //this is the exponent math for the end of the equation
if (t < 0) {
t = t*(-1); //this is the absolute value for temperature
}
double w = (35.74 + 0.6215*t)+((0.4275*t - 35.75)* x); //this is the actual calculation
if (t<=50 && v>3 && v<120) { //this is so the code runs only when the equation works
System.out.println(w);
}
if (t>50 || v<3 || v>120){
System.out.println("The wind chill equation doesn't work with these inputs, try again.");
}
}
}
This gives me an ArrayIndexOutOfBounds error. It doesn't matter what I put in the [] I get an error... why? and how can I fix it?
The reason is
int t = Integer.parseInt(args[44]);
Do you have 45 arguments?
The problem here is the way in which you are creating the arrays:
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args refers to the command line arguments that are passed to the main() method of your program. If you try to parse args[44] when there aren't 45 arguments (0 indexing, remember ?) you will end up assigning null to your array.
So, all you will later end up with is an ArrayIndexOutOfBoundsException becuase you cannot index a null array.
int t[] = new int[44]; // please notice the brackets
int v[] = new int[15]; //this is the array input for wind speed
The above method shall suffice if all you need is the size
Arrays in Java are int[] t or int t[]. Either of them will do but the brackets need to be there.
Use Math.abs() to find the absolute value. Saves you the if()
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args i.e. args is the command line arguments for main method. Do you have 45 elements inside the args if not than it will throw ArrayIndexOutOfBounds.
To know the length please use:
args.length
Than you can proceed. Hope it helps.
In these lines :
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
You say that you run your program with at least 45 parameters!! where on the 15. place is wind speed and on the 44. is temperature.
You probably running program with NO parameters at all or with one.
Note that if you run program with parameters : "hello world how are you" the program would have args of size 5 with having hello in args[0], world in args[1] etc.
What you have now is:
- take the 15th command line argument and cast to to Integer;
- take the 44th command line argument and cast it to Integer.
Are you sure that it is what you need?
Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.