欢迎来到Java SE练习题频道,我是Fishing,今天我带来的练习题是(作题会有不足之处,可评论,说出更好的方法):java
看到这题,我首先敲出了main函数。 : )函数
public static void main(String[] args) { // 代码部分 }
首先,键盘输入嘛,获取控制台的信息,import Scanner包,实例化对象:spa
import java.util.Scanner; public class Test { static Scanner sc = new Scanner(System.in); public static void main(String[] args){ // 代码部分 } }
读入两个数:代码规范
// 获取信息 System.out.println("请输入第一个整数:"); int i1 = sc.nextInt(); System.out.println("请输入第二个整数:"); int i2 = sc.nextInt();
呵呵,我到这一步懵了。。。code
首先,一“堆”好的代码不只要有代码规范,还要有注释、思路。我一想,要先判断输入的数的大小,在判断小的数是否为奇数,再用循环。。。对象
// 判断小的数是否为奇数 if (small % 2 == 1) { small++; small++; } else { small++; }
而后,我有用了循环,将全部之间的奇数都列出来而后将返回值不断增长,最后,呵呵,,,blog
// 算出结果 int result = 0; while (small < big) { result += small; // 加2 small++; small++; } return result;
完美,,,get
完整代码:class
import java.util.Scanner; /** * 做者: Fishing * 时间: 2018-05-23 * 概述: 经过键盘输入两个整数,计算这两个整数之间的全部奇数之和,并输出计算结果。 */ public class Demo { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // 获取信息 System.out.println("请输入第一个整数:"); int i1 = sc.nextInt(); System.out.println("请输入第二个整数:"); int i2 = sc.nextInt(); // 判断两个数的大小 if (i1 >= i2) { System.out.println(getResult(i2, i1)); } else { System.out.println(getResult(i1, i2)); } } private static int getResult(int small, int big) { // 判断小的数是否为奇数 if (small % 2 == 1) { small++; small++; } else { small++; } // 算出结果 int result = 0; while (small < big) { result += small; // 加2 small++; small++; } return result; } }
此次的题目分享就到这里,谢谢看完。。。import