If you started attending a vocational training school and learned HTML & CSS, Java with Progate etc., you can use Qiita completely ... so I tried to describe the exercises of "** Introduction to Java that is refreshing, 2nd edition **" that I purchased for studying Java in a different way from the original answer.
Practice 2-3 Create the following program.
① "Welcome to the fortune-telling hall" is displayed on the screen. ② The message "Please enter your name" is displayed on the screen. (3) Accepts one line of character input from the keyboard and stores it in the String type variable name. ④ "Please enter your age" is displayed on the screen. ⑤ Accepts one line of character input from the keyboard and stores it in the String type variable ageString. (6) Convert the contents of the variable ageString to an int type and assign it to the int type variable age. (7) Generate a random number from 0 to 3 and assign it to the int type variable fortune. ⑧ Increase the value of fortune by 1 with the increment operator to make it a random number from 1 to 4. ⑨ "The result of fortune-telling has come out!" Is displayed on the screen. ⑩ The screen will display "(age) year old (name), your luck number is (random number)". At that time, the variable age is displayed in (age), the variable name is displayed in (name), and the number created in ⑧ is displayed in (random number). "1: Daikichi 2: Nakayoshi 3: Kichi 4: Bad" is displayed on the screen.
import java.util.*;
public class practice {
public static void main(String[] args) {
Scanner stdInput = new Scanner(System.in);
Random random = new Random();
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "Daikichi");
map.put(1, "Nakayoshi");
map.put(2, "Kichi");
map.put(3, "Bad");
System.out.println("Welcome to the fortune-telling hall!");
System.out.print("Please input your name:");
String name = stdInput.nextLine();
System.out.print("Please enter your age:");
String ageString = stdInput.nextLine();
int age = Integer.parseInt(ageString);
int fortune = random.nextInt(4);
System.out.println("\n Fortune-telling results have come out!");
System.out.println(age + "of age" + name + "San, your fortune" + map.get(fortune) + "is");
}
}
Execution result
result
Welcome to the fortune-telling hall!
Please enter your name: Hatademeo
Please enter your age: 40
The result of fortune-telling came out!
40-year-old Hatademeo, your fortune is Nakayoshi
Introduction to Java that is refreshingly understood 2nd edition (refreshing series)
I was told to do various things, but this is the result of ignoring it. .. .. I wanted to use a Python dictionary, but the first thing I looked up was ** Map **, so I used that. It's quite annoying for java to declare data types in various places. .. .. It should be easy to understand
Please do not hesitate to point out any points you notice.
Recommended Posts