package zh.codegym.task.task06.task0606;
import java.io.*;
/*
偶数和奇数
*/
public class Solution {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
//在此编写你的代码
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
System.out.println(evo(a));
}
public static String evo(int a){
String s = String.valueOf(a);//将a转为字符串;
int length = s.length();//获取字符串的长度;
for (int i = 0; i < length; i++) {
int x = Integer.parseInt(s.substring(i,i+1));//截取在i位置上的字符串,并转换为int型;
//按位执行判断
if (x%2==0){
even++;
}else {
odd++;
}
}
return "偶数:"+even+" 奇数:"+odd;
}
}
评论 (7)
- 受欢迎
- 新
- 旧
你必须先登录才能发表评论
wedfrgt
24 二月 2021, 12:08
我用了一大段来处理分割int类型(取模),却发现有个substring方法。。。
0
温柔
25 二月 2021, 12:02
哈哈哈哈哈,我刚开始也是这么想的,后来想到了除以10取余数
0
温柔
23 二月 2021, 07:04
这是我修改后的代码
0
Guadalupe Gagnon
23 二月 2021, 14:25
Take line 5 and 8 out of this code and move it to in between line 9-10:
Whenever you have the same line of code appearing in multiple locations, you can typically rearrange the logic flow to get a point where you only need one of those lines ( such as in this case).
When you get 5 or 6 lines together that repeat in multiple places, you can put those lines into a method and then use the method to replace the repeats. 0
温柔
24 二月 2021, 10:51
Thanks very much😊
0
Guadalupe Gagnon
22 二月 2021, 18:29
While learning it is fine to solve things any way that you can. As you continue learning you will advance in your understanding on how computers process information and the best ways to manipulate that information. With that, just accept that any solve at this point in your learning is a good solve.
I have one thing that could potentially make your code better though:
- line 16a it reads a String from the keyboard
- line 16b and converts it to an int
- line 17 it passes that int to the evo() method
- line 21 it convert the int back to a String
- line 24 it takes each char from the String and converts it back to an int
This code does one thing, reverses it, then does it again. If you want to upgrade I would suggest removing 2 of those step.
0
温柔
23 二月 2021, 06:39
thanks
0