The goal of this code is simply to find the max of the numbers in list a and multiply it by 1.5 The first input decides the amount of numbers the user enters. The second input is a double which are the numbers. I have used an array to collect my numbers and find max from it.
I have written the below code however I am not getting the right max value. Can you please let me know where I am going wrong? and also please feel to comment if I am not following right way of coding as I am pretty new to it.
My data is
10
750.55
1555.99
524.12
5268.00
789.4569 // program shows this a max value
1245.78
124.556
175.56
1796.46
7564.994
Below is my code:
class Main {
static void main(String[] args) {
Scanner sc = new Scanner(System.in)
def NoofTrans = Integer.parseInt(sc.nextLine())
def Transamt = [NoofTrans]
for (int i = 0; i < NoofTrans; i++) {
Transamt[i]=sc.nextLine()
}
def Creditlimit
println Transamt.max()
Creditlimit=Transamt.max().toDouble()
def Creditlimit1=(Creditlimit*5)
println Creditlimit1
println Creditlimit1.round(2)
}
}
My output is below
789.4569
1184.19
whereas it should be
7564.994
11347.49
There are two problems:
1 - You've mixed numbers and strings in the same list. So the max you found did not use numerical comparison. You need to use nextDouble()
for Scanner to give you a number:
Transamt[i] = sc.nextDouble();
2 - Your code is multiplying max by 5
whereas you want to multiply it by 1.5
. This just produced unexpected results.
Here's the full code:
class MainGroovy {
static void main(String[] args) {
Scanner sc = new Scanner(System.in)
def NoofTrans = Integer.parseInt(sc.nextLine())
def Transamt = [NoofTrans]
for (int i = 0; i < NoofTrans; i++) {
Transamt[i] = sc.nextDouble()
}
println Transamt.max()
def Creditlimit = Transamt.max()
def Creditlimit1 = Creditlimit * 1.5
println Creditlimit1
println Creditlimit1.round(2)
}
}
When executed with your input, the output is:
7564.994
11347.491
11347.49
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.