+ 1
How many ways can we make the code shorter?
11 Antworten
+ 5
This could be even shorter... if you don't include the import static line. 😉
----
import java.util.Scanner;
import static java.lang.System.out;
public class S {
public static void main(String[] args) {
out.println((new Scanner(System.in))
.nextInt() * 29030400);
}
}
+ 4
https://code.sololearn.com/cX96mFN5ZGCk/?ref=app
Try this , all things in one line 🤣!! This is also one way! RIP readibilty 😔!
Well all have written 29030400secs , Abdul-Quadri if you feel problems to find calculation you can simpley do like this (years*12*4*7*24*60*60)
+ 3
https://code.sololearn.com/c4S491urbRvj/?ref=app
//Check this
+ 2
// or even shorter:
import java.util.Scanner;
public class ScannerExcercise {
public static void main(String[] args) {
Scanner Year = new Scanner(System.in);
System.out.println(Year.nextInt() * 29030400);
}
}
+ 2
David Carroll Can you please explain me that code?
+ 2
class Program {
public static void main(String[] args) {
System.out.print(new java.util.Scanner(System.in).nextInt() * 29030400);
}
}
Even better, no imports at all.
+ 2
Atul What you mean by "predefined methods without importing their packages?"
What's an example of a predefined method?
+ 2
Atul yes, we can live without importing but too much of that can make the code look cumbersome.
+ 1
Atul There not much to explain really... which I think was the point. 😉
I actually simplified the version by visph who simplified your version.
So... I'll compare your version with mine.
out.println((new Scanner(System.in))
.nextInt() * 29030400);
First, I was able to use:
out.println()
Without fully qualifying as:
System.out.println()
By using the import static line at the top of my code.
Second, rather than assigning:
new Scanner(System.in)
... to a variable, I just invoke the nextInt() method directly off the instance that's returned from calling the constructor.
This works if you plan on using the Scanner only once, as is the case here.
Likewise, nextInt() returns an int which can be referenced immediately without assigning to a variable because it's used only once.
We then multiply the value from nextInt() with the product of all the other values:
(12 * 4* 7 * 24* 60* 60)
is 29030400
Essentially resulting as:
println(nextInt() * 29030400)
+ 1
David Carroll so can we use the predefined methods without importing their packages?
+ 1
Soumik [Busy] yes I was expecting this. David sir mentioned it correct I asked this question to him