java从命令行输入一个数,输出其包含数值相邻相加的和等于输入的数字

来源:互联网 发布:零投资网络赚钱项目 编辑:程序博客网 时间:2024/05/16 04:23

 

例如:数字:15

输出:15=[1, 2, 3, 4, 5]
         15=[4, 5, 6]
         15=[7, 8]

         数据:16 没有

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class TestNumber {
 public void checkNumber(int num)
 {
  if(num<2)return ;
  int temp=0,j=1;
  ArrayList list =new ArrayList();
  boolean tag=false;
  int count=1;
  while(j<num){
   for(int i=count;i<num;i++){
    temp+=i;
    list.add(i);
    if(temp==num){
     System.out.println(num+"="+list);
     tag=true;
    }
   
   }
   count++;
   list=new ArrayList();
   temp=0;
   j++;
  }
  if(!tag){
   System.out.println("没有");
  }
  
 }
 public static void main(String []args){
         String str="";
         int a=0;
         BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
         boolean tag=true;;
         while(tag)
         {
           System.out.println("请输入一个数:");
         try {
    str=buf.readLine();
   } catch (IOException e) {
    e.printStackTrace();
   }
   tag=false;
   try{
         a=Integer.parseInt(str);
   }catch(Exception ex ){
    System.out.println("请输入正常的数字格式!");
    tag=true;
   }
  
     }
  TestNumber test=new TestNumber();
  test.checkNumber(a);
 }

}

原创粉丝点击