Can I shorten this code? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 3

Can I shorten this code?

Hello! This is my first code and i wanted to know is it possible to shorten this code? https://code.sololearn.com/c4s05GtD8SKR/?ref=app I'm created the simple Magic 8-Ball. Have fun and good luck!

11th Mar 2018, 11:41 PM
Dzmitry Ausiannikau
Dzmitry Ausiannikau - avatar
4 ответов
+ 4
As @J.G. stated you can use an array: int max = 19; String[] answers = { "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Dont count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" }; System.out.println(answers[(int)(Math.random() * max)]);
12th Mar 2018, 12:16 AM
ChaoticDawg
ChaoticDawg - avatar
+ 7
Put all the answers in an array and select a random bucket from the array
11th Mar 2018, 11:45 PM
J.G.
J.G. - avatar
+ 4
What I would suggest is that instead of using several if statements over and over is that you use a switch statement. This should help make the code a little shorter and make it easier to read and understand. Here's Sololearn's lesson on switch statements in Java - https://www.sololearn.com/learn/Java/2145/ d:
12th Mar 2018, 12:08 AM
Faisal
Faisal - avatar
+ 4
As J.G. said, array. To begin with, your variable, a, is unnecessary.
12th Mar 2018, 12:13 AM
non