1. 程式人生 > >java語言中,輸入A,B輸出A+B的值

java語言中,輸入A,B輸出A+B的值

問題如下:
計算一對A、B的和或者計算多對A、B值的和;

輸入格式:

輸入的第一行包括兩個數(即A,B對,中間用空格隔開),也可以在第一行輸入多個A、B對;

輸出格式:

對於輸出的A、B中的和要與輸入的A、B對一一對應,並且A+B獨自佔一行; 1.每次只輸入一對A、B時,程式碼如下:
public class Main
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
           //獲取在控制檯輸入的字串,System.in是調入輸入的字串
	    Scanner cin=new Scanner(System.in);  
	    Integer a=cin.nextInt();  
            Integer b=cin.nextInt();  
            System.out.println(a+b); 
    }  
}
輸出結果為: 1 5
6

2.每次可以輸入多個A、B對,程式碼如下
public class Main
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		//獲取在控制檯輸入的字串,System.in是調入輸入的字串
		Scanner cin=new Scanner(System.in);  
		//使用while迴圈判斷是否有下一個輸入
           while(cin.hasNext()){  
              int a=cin.nextInt();  
              int b=cin.nextInt();  
              System.out.println(a+b);  
        }  
    }  
}

輸出結果為: 1 1
2


1 2
3


1 3
4
3.對於輸入的A、B對有限制的,比如只讓輸入三對; 解決方法是:第一次輸入一個整數N,這個N表示可以輸入幾行A、B對,A、B用空格隔開 程式碼如下:
public class Main1
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		//獲取在控制檯輸入的字串,System.in是調入輸入的字串
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		//使用while迴圈對N進行迴圈
		while (n-- > 0) 
		{
			String s1=scanner.next();
			String s2=scanner.next();
			BigInteger b1=new BigInteger(s1);
			BigInteger b2=new BigInteger(s2);
			
			System.out.println(b1.add(b2).toString());
//			int b1=scanner.nextInt();
//			int b2=scanner.nextInt();
//			System.out.println(b1+b2);
			
		}
	}
}

執行結果如下: 2
1 1
2


1 2
3
4.對於最後一行輸入的A、B對是0 0時,計算立刻結束,並且最後一行不要計算,程式碼如下:
public class Main3
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		 Scanner cin=new Scanner(System.in);   
	        int a=0,b=0;  
	        while(cin.hasNext()){    
	          if((a=cin.nextInt())==0||(b=cin.nextInt())==0)  
	          break;  
	          System.out.println(a+b);    
	        }    
	    }    
	}
執行解果: 1 2
3


1 3
4


0 0

5.計算若干整數的和 要求:每行的第一個數N,表示這一行有N個數,如果N等於0,表示輸入結束,這一行不計算;程式碼如下:
public class Main2
{

	 public static void main(String[] args) {  
	       Scanner cin = new Scanner(System.in);  
	       while(cin.hasNext()){  
	         int a,b=0,c=cin.nextInt();  
	        // System.out.println("c--->"+c);
	           if(c==0){  
	               return;  
	           }  
	           for(int i=0;i<c;i++){  
	               a=cin.nextInt();  
	               //System.out.println("a="+a);
	               //b+=a;
	               b=b+a;
	           }  
	           System.out.println(b);  
	             
	       }  
	    }  
}
執行結果如下: 2 1 1
2


3 1 2 3
6


0 1 1