2016-05-10 153 views
1

我做了一个程序,要求用户输入5位数字,然后程序找到这些数字的总和。 我想知道如何让程序在计算一次后再次请求一个数字。 我希望用户再次尝试n直到他自己想要退出。继续执行程序

public static void main(String[] args) { 

    int num=1362; 
    int i,t=0; 
    int store; 

    for(i=0; i<=5; i++) 
    { 

     store=num%10; 
     num=num/10; 
     t=t+store; 

    } 

    System.out.println("The sum of the digits of 1362 is " +t); 
} 
+0

用户如何停止执行?使用关键字? – FedeWar

+2

使用循环。尝试使用伪代码将其写在纸上,然后尝试为此编写Java代码。发布你的尝试,我们将尝试纠正你的错误。 – Pshemo

+0

尝试一个do-while循环。设置一个keyworkd退出,另一个继续,向用户询问他是否要退出,如果没有按c键,请按x(例如) –

回答

1

直到用户写入非数字的东西时,执行才会继续。

public static void main(String[] args) { 
    int num=1362; 
    int i,t=0; 
    int store; 
    Scanner in = new Scanner(System.in); 
    while(in.hasNextInt()) 
    { 
     t = 0; 
     store = 0; 
     num = in.nextInt(); 
     for(i=0; i<=5; i++) 
     { 
      store=num%10; 
      num=num/10; 
      t=t+store; 
     } 
     System.out.println("The sum of the digits is " +t); 
    } 
    in.close(); 
} 
+0

虽然这个程序碰巧正在退出,所以它没有任何作用,关闭与'System.in'绑定的'Scanner'通常不是一个好主意。在这里关于为什么输入不再被读取的问题有很多,并且他们追踪到在stdin上关闭扫描器。 – KevinO

1

我的解决办法: 用户输入5个号码,之后,总和计算,如果他要重复它(没有异常处理),要求用户。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

String repeat = ""; 
do { 
    try { 
     int[] digits = new int[5]; 
     System.out.println("Enter 5 digits: "); 

     for (int i = 0; i < digits.length; i++) { 
      System.out.printf("Digit %d:", i + 1); 
      String input = br.readLine(); 
      digits[i] = Integer.parseInt(input); 
     } 

     int sum = 0; 
     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < digits.length; i++) { 
      sum += digits[i]; 
      sb.append(digits[i]); 
     } 

     System.out.printf("The sum of the digits of %s is %d.", sb.toString(), sum); 
     System.out.println("Repeat? (y/n)"); 
     repeat = br.readLine(); 

    } catch (NumberFormatException e) { 
     // TODO: handle wrong user input 
    } catch (IOException e) { 
     // TODO: handle io exception 
    } 
} while (repeat.equals("y")); 

try { 
    br.close(); 
} catch (IOException e) { 
    // TODO: handle IOException 
}