使用变量完成自我个绍 创建姓名、年龄、爱好等变量,使用输出语句将结果打印到控制台 得出预计结果后尝试优化和调整代码编写方式
时间: 2024-04-12 19:28:59 浏览: 19
Sure! Here's an example of how you can use variables to introduce yourself:
```java
public class SelfIntroduction {
public static void main(String[] args) {
String name = "Alice";
int age = 25;
String hobby = "reading";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Hobby: " + hobby);
}
}
```
In this code, we have created variables `name`, `age`, and `hobby` to store the corresponding information. We then use the `System.out.println()` statement to print the values of these variables to the console.
After running this code, you will see the following output:
```
Name: Alice
Age: 25
Hobby: reading
```
To optimize and improve the code, you can consider using formatted strings or concatenation for better readability. Here's an updated version:
```java
public class SelfIntroduction {
public static void main(String[] args) {
String name = "Alice";
int age = 25;
String hobby = "reading";
System.out.printf("Name: %s%n", name);
System.out.printf("Age: %d%n", age);
System.out.printf("Hobby: %s%n", hobby);
}
}
```
In this version, we use formatted strings (`%s` for string, `%d` for integer) and the `%n` symbol for line breaks. This makes the code more concise and easier to modify if needed.
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)