本帖最后由 杨健yj 于 2012-8-15 00:52 编辑
自己写的代码,里面能排除非法字符,并打印出数组,和最后的结果 ,如果输入over就结束程序- import java.util.Scanner;
- public class diGui {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc = null;
- int num = 0;
- int n = 0;
- System.out.println("请输入一个数字");
- boolean falge = true;
- while (falge) {
- sc = new Scanner(System.in);
- if (sc.hasNextInt()) {
- num = Math.abs(sc.nextInt());
- System.out.println("请再输入一个数:");
- while (falge) {
- sc = new Scanner(System.in);
- if (sc.hasNextInt()) {
- n = Math.abs(sc.nextInt());
- print(num, n);
- System.out.println(sum(num, n));
- break;
- } else if (sc.hasNext("over")) {
- break;
- } else {
- System.out.println("请输入正确的数字,请不要输入字符");
- }
- }
- System.out.println("请输入一个数字:");
- continue;
- } else if (sc.hasNext("over")) {
- break;
- } else {
- System.out.println("请输入正确的数字,请不要输入字符");
- }
- }
- }
- // 打印这个序列
- public static void print(int num, int n) {
- int i = 1;
- int[] arr = new int[1024];
- arr[0] = num;
- if (n <= 0) {
- System.out.println("n不能小于等于0!!!");
- } else {
- if (n == 1) {
- System.out.println("[" + arr[0] + "]");
- } else {
- System.out.print("[");
- System.out.print(arr[0] + ",");
- int sum = 0;
- while (i < n) {
- arr[i] = (int) (num * Math.pow(10, i)) + arr[i - 1];
- if (i == n - 1) {
- System.out.print(arr[i] + "]");
- } else {
- System.out.print(arr[i] + ",");
- }
- i++;
- }
- }
- }
- }
- public static int sum(int num, int n) {
- int i = 1;
- int[] arr = new int[1024];
- arr[0] = num;
- int sum = 0;
- while (i < n) {
- arr[i] = (int) (num * Math.pow(10, i)) + arr[i - 1];
- // System.out.println("---"+arr[i]);
- i++;
- }
- for (int j = 0; j < arr.length; j++) {
- sum = sum + arr[j];
- }
- return sum;
- }
- }
复制代码 |