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.
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;
}
I am very new to java and I set a goal for myself to make a dice rolling program (keeping it small). The end goal is to be able to roll a user-selected amount of dice and be able to have each die have a different amount of side if need be and I have it get the number of dice and how many sides each has. This is the code I made for it (Might be really bad, sorry if it is) :
public class Roller {
public final Random rando;
public final int faces;
public Roller(int faces) {
this.rando = new Random();
this.faces = faces;
}
public int roll() {
return 1 + rando.nextInt(faces);
}
//above code is not mine I built off what my friend wrote cause i didnt know if i still need it
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
System.out.print("How many dice do you want to roll?\n");
int D6 = scan.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < D6; i++) {
System.out.print("How many sides does die " + (i + 1) + " have?\n");
Roller dice = new Roller(scan.nextInt());
list.add(dice.roll());
}
}
}
Now I'm at the point where I want to display the ArrayList but I want to display it as
"Dice 1 rolled #
Dice 2 rolled #"
etc. and I'm lost on how to do that especially with the varying number of dice. Any help is very appreciated.
Let's assume you ran this and now have a List of values, [1, 3, 5, 2, 4] and you want to display them as you described.
In your main method, you have the list, so you could do some looping and string formatting to get your desired output. (edited to use printf() rather than String.format())
// in main...
// after list has all it's values
for (int i = 0; i < list.size(); i++) {
System.out.printf("Dice #%d rolled %d", i+1, list.get(i));
}
Note that the below statements are still valid, and can still be applied to printf(...)
To walk through it, String formatting is just a fancy way to format your strings (funny how that works out). The first %d corresponds to the first value given to format(), which is i+1. It's i+1 as opposed to plain i because otherwise you'd see "Dice #0 rolled ..." first, since you start indexing arrays and lists at 0. With the second %d in the format() call, you pass in list.get(i) which is the value in the list at the given index. This should correspond nicely to the order of the rolls.
This didn't have to be done with String formatting. I find it tends to be better and easier to read personally, but it is easily substituted with String concatenation.
//replace the print statement with this if you want
System.out.println("Dice #" + (i+1) + " rolled " + list.get(i));
It seems sloppier to me IMO, and needing to remember to leave spaces, or omit spaces between concatenated parts can be annoying.
So here is the code I have right now.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.
The x's are just the generated random numbers by the way.
How do I keep doing this? It has to be a total of utmost 5 times.
Here are the basic steps you should follow to accomplish what you want/need.
Read user input (using Scanner or something else).
Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).
The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.
For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.
The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.
In your case
for (Die die : dice) {
die.roll();
}
where class Die looks like
public class Die {
private int value;
public Die() {
roll();
}
public void roll() {
value = (int)(Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)
List<Die> dice = new ArrayList<>();
Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.
When you really can't get around using them, use a for loop to walk each array index.
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.
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;