Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Уймин Максим
- //IT School, 2 группа
- //09.10.2015
- //Задача 2. Вычислить сумму элементов строк/столбцов
- import java.io.PrintStream;
- import java.util.Scanner;
- public class Exersise_2 {
- public static PrintStream out = System.out;
- public static Scanner scan = new Scanner(System.in);
- public static int [][] CreateMatrix (int I){
- //Функция создаёт матрицу по заданным с клавиатуры данным, заполняет её случайными числами
- int matrix[][] = new int [I][];
- for (int i = 0; i<I;i++){
- matrix[i] = new int [I];
- }
- for (int i = 0; i<I;i++){
- for (int j = 0; j<I;j++){
- matrix[i][j]=(-10) + (int)(Math.random()*((10-(-10))+1));
- }
- }
- return matrix;
- }
- public static void PrintMatrix(int[][]matrix,int I){
- //Функция выводит матрицу на экран
- for (int i=0;i<I;i++){
- for (int j=0;j<I;j++){
- out.print(matrix[i][j]+"\t");
- }
- out.println();
- }
- }
- public static int Sum(int[][]matrix,int I){
- //Функция находит сумму элементов строки или столбца
- out.println("Should I sum 1.strings or 2.columns? (enter the number of the correct answer)");
- int answer = scan.nextInt();
- int sum = 0;
- while (answer !=1 && answer!=2){
- out.println ("Wrong command, try again");
- out.println("Should I sum 1.strings or 2.columns? (enter the number of the correct answer)");
- answer = scan.nextInt();
- }
- if (answer == 1) sum = SumStrings(matrix,I);
- else if (answer == 2) sum = SumColumns(matrix,I);
- return sum;
- }
- public static int SumStrings(int[][]matrix,int I){
- //Функция находит сумму элементов строки
- int sum=0;
- out.println("Choose number of string, where I should sum the elements (number must be integer, greater than zero and less than matrix size)");
- int N = scan.nextInt();
- N--;
- while (N<0 || N>I){
- out.println ("Wrong number, try again");
- N = scan.nextInt();
- }
- for (int i=0;i<I;i++){
- sum=sum+matrix[N][i];
- }
- return sum;
- }
- public static int SumColumns(int[][]matrix,int I){
- //Функция находит сумму элементов строки
- int sum=0;
- out.println("Choose number of column, where I should sum the elements (number must be integer, greater than zero and less than matrix size)");
- int N = scan.nextInt();
- N--;
- while (N<0 || N>I){
- out.println ("Wrong number, try again");
- N = scan.nextInt();
- }
- for (int i=0;i<I;i++){
- sum=sum+matrix[i][N];
- }
- return sum;
- }
- public static void MainFunction (){
- //Здесь собран весь функционал программы
- out.println("Enter the matrix size (integer number and greater than zero)");
- int I = scan.nextInt();//Считываем размер матрицы
- int[][]matrix = CreateMatrix(I);
- out.println("Original matrix:");
- PrintMatrix(matrix,I);
- int sum = Sum(matrix,I);
- out.println("Sum is"+sum);
- }
- public static void main (String [] args){
- //Основная функция, отсюда начинается выполнение приложения
- MainFunction();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement