StudyTonight Java 中文教程(十四)

原文:StudyTonight

协议:CC BY-NC-SA 4.0

Java 程序:求商和余数

原文:https://www.studytonight.com/java-programs/java-program-to-find-quotient-and-remainder

在本教程中,我们将学习如何通过接受用户的输入来找到商和余数。但是在继续之前,如果你不熟悉 java 中算术运算符的概念,那么一定要查看关于 Java 中运算符的文章。

**输入:**输入第一个数字:6

输入第二个数字:2

输出:

6 和 2 的商是 3

6 和 2 的余数是 0

上述问题可以通过以下方式解决:

方法 1:当值被预定义时

方法 2:当值由用户定义时

让我们分别看看这些方法。

程序 1:求商和余数

在这个程序中,当两个数字是用户定义的时,我们将找到它们的商和余数。

算法:

  1. 开始
  2. 声明两个变量。
  3. 初始化变量。
  4. 用除法运算符求商。
  5. 使用模运算符求余数。
  6. 显示商和余数。
  7. 停下来。

下面是相同的代码。

//Java Program to find the quotient and remainder
public class Main 
{
    public static void main(String[] args) 
    {
        int num1 = 19, num2 = 4;  //Declare and initialize the numbers
        System.out.println("The entered number is: "+num1);
        System.out.println("The entered number is: "+num1);
        int quotient = num1 / num2;   //Find quotient
        int remainder = num1 % num2;  //Find Remainnder
        System.out.println("After division the quotient and remainder are: ");
        //Print the quotient and remainder
        System.out.println("The quotient is: " + quotient);
        System.out.println("The remainder is: " + remainder);
    }
} 

输入的数字是:19
输入的数字是:19
除法后的商和余数是:
商是:4
余数是:3

程序 2:求商和余数

在这个程序中,当两个数字是用户定义的时,我们将找到它们的商和余数。这意味着,在这里,首先我们将要求用户初始化数字,然后我们将找到商和余数。

算法:

  1. 开始
  2. 创建 Scanner 类的实例以从用户处获取输入。
  3. 声明两个变量。
  4. 请用户初始化它。
  5. 用除法运算符求商。
  6. 使用模运算符求余数。
  7. 显示商和余数。
  8. 停下来。

下面是相同的代码。

//Java Program to find the quotient and remainder
import java.util.*;
public class Main 
{
    public static void main(String[] args) 
    {
        //Take input from the user
        //Create object of Scanner class
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the numbers ");
        System.out.println("Enter the first number: ");
        int num1=sc.nextInt();  //Initialize the number
        System.out.println("Enter the second number: ");
        int num2=sc.nextInt();  //Initialize the number
        int quotient = num1 / num2;
        int remainder = num1 % num2;
        System.out.println("After division the quotient and remainder are:");
        //Print the Quotient 
        System.out.println("The quotient is: " + quotient);
        System.out.println("The remainder is: " + remainder);
    }
} 

输入数字
输入第一个数字:19
输入第二个数字:7
除法后商和余数为:
商为:2
余数为:5

程序 3:求商和余数

在这个程序中,我们将使用用户定义的方法,用用户定义的输入来求商和余数。

算法:

  1. 开始
  2. 创建 Scanner 类的实例以从用户处获取输入。
  3. 声明两个变量。
  4. 请用户初始化它。
  5. 调用用户定义的方法来求商和余数。
  6. 用除法运算符求商。
  7. 使用模运算符求余数。
  8. 显示商和余数。
  9. 停下来。

下面是相同的代码。

//Java Program to find the quotient and remainder
import java.util.*;
public class Main 
{
    public static void main(String[] args) 
    {
        //Take input from the user
        //Create object of Scanner class
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the numbers ");
        System.out.println("Enter the first number: ");
        int num1=sc.nextInt();  //Initialize the number
        System.out.println("Enter the second number: ");
        int num2=sc.nextInt();  //Initialize the number
        findQuotient(num1,num2);
    }
    //user defined method
    static void findQuotient(int num1, int num2)
    {
       int quotient=num1/num2;
       int remainder=num1%num2;

       //display result
       System.out.println("The quotient of "+num1+" and "+num2+" is "+quotient);
       System.out.println("The remainder of "+num1+" and "+num2+" is"+remainder);

    }
} 

输入数字
输入第一个数字:9
输入第二个数字:7
9 和 7 的商是 1
9 和 7 的余数是 2



Java 程序:检查偶数和奇数

原文:https://www.studytonight.com/java-programs/java-program-to-check-even-and-odd-number

在本教程中,我们将学习如何检查输入的数字是偶数还是奇数。偶数是能被 2 整除的数,不能被 2 整除的数称为奇数。这里,在这个程序中,我们将检查这个数是否能被 2 整除。如果能整除,那么它就是偶数,如果不能整除,那么它就是奇数。但是在继续之前,如果你不熟悉 java 中条件语句的概念,那么一定要查看条件语句上的文章。

**输入:**输入数字:6

**输出:**输入的数字为偶数。

程序 1:检查数字是偶数还是奇数

在这个程序中,我们将看到当数字是用户定义的时,如何检查数字是偶数还是奇数。这意味着,这里我们将首先要求用户输入数字,然后我们将检查输入的数字是偶数还是奇数。

算法

  1. 开始

  2. 创建一个 Scanner 类的对象,从用户那里获取输入。

  3. 声明一个变量来存储数字。

  4. 要求用户初始化数字。

  5. 检查这个数是否能被 2 整除。

  6. 如果数字能被 2 整除,那么输入的数字就是偶数。

  7. 如果输入的数字不能被 2 整除,那么输入的数字就是奇数。

  8. 显示输出。

  9. 停下来。

下面的例子说明了上述算法的实现。

/*Java Program to check whether a number is even or odd*/
import java.util.Scanner;

public class Main
{
  public static void main(String args[])
  {
    //To take input from the user 
    //Create an object of scanner class
    Scanner input = new Scanner(System.in);
    int num;  //Declare a variable
    System.out.println("Enter a number:");
    num = input.nextInt();

    //If number is divisible by 2 then it's an even number
    //else odd number
    if ( num % 2 == 0 )
        System.out.println("The entered number is even");
     else
        System.out.println("The entered number is odd");
  }
}

输入数字:6
输入的数字是奇数

程序 2:检查数字是偶数还是奇数

在这个程序中,我们将看到如何使用三进制运算符检查数字是偶数还是奇数。这意味着,首先我们将要求用户输入数字,然后使用三进制运算符检查输入的数字是偶数还是奇数。

算法:

  1. 开始

  2. 创建一个 Scanner 类的对象,从用户那里获取输入。

  3. 声明一个变量来存储数字。

  4. 要求用户初始化数字。

  5. 使用三进制运算符检查输入的数字是偶数还是奇数。

  6. 如果输入的数字能被 2 整除,那么它就是偶数,否则就是奇数。

  7. 显示结果。

  8. 停止

下面的例子说明了上述算法的实现。

/*Java Program to check whether a number is even or odd*/
import java.util.Scanner;

public class Main
{
  public static void main(String args[])
  {
    //To take input from the user 
    //Create an object of scanner class
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int num = sc.nextInt();
    //Use Ternary Operator to check
    String check = (num % 2 == 0) ? "even" : "odd";

    System.out.println("The entered number "+ num + " is: " + check);

  }
}

输入数字:5
输入的数字 5 是:奇数

程序 3:检查数字是偶数还是奇数

在这个程序中,我们将看到如何使用按位异或来检查数字是偶数还是奇数。使用这种方法的逻辑是,偶数的按位异或运算将数字的值增加 1,否则,如果值为奇数,它将数字的值减少 1。

算法

  1. 开始

  2. 创建一个 Scanner 类的对象,从用户那里获取输入。

  3. 声明一个变量来存储数字。

  4. 要求用户初始化数字。

  5. 使用按位异或检查数字是偶数还是奇数。

  6. 如果与 1 按位异或后的数等于原数+ 1,则为偶数。

  7. 如果不相等,那么它就是一个奇数。

  8. 显示结果。

  9. 停下来。

下面的例子说明了上述算法的实现。

/*Java Program to check whether a number is even or odd*/
import java.util.Scanner;

public class Main
{
  public static void main(String args[])
  {
    //To take input from the user 
    //Create an object of scanner class
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int num = sc.nextInt();
    //Check Using Bitwise XOR
    if ((num ^ 1) == num + 1) 
    { 
         System.out.println("The entered number "+ num +" is Even"); 
    } 
    else 
    { 
        System.out.println("The entered number "+ num +" is Odd"); 
    } 

  }
}

输入数字:52
输入的数字 52 为偶数



Java 程序:检查字符串是否为空或null

原文:https://www.studytonight.com/java-programs/java-program-to-check-if-a-string-is-empty-or-null

在本教程中,我们将学习如何检查字符串是否为空。这可以通过各种方法来实现,比如如果输入的字符串长度为 0,那么它就是一个空字符串。我们还可以使用各种预定义的方法,如 equals(),isEmpty(),等来检查字符串是否为空。但是在进一步深入之前,如果你不熟悉字符串的概念,那么一定要查看 Java 中Strings的文章。

**输入:**输入字符串:苹果

**输出:**输入的字符串为空?:假

程序 1:检查字符串是否为空

在这个程序中,我们将学习如何使用关系运算符检查字符串是空的还是空的。

算法:

  1. 开始

  2. 声明一个字符串。

  3. 用一些值初始化它。

  4. 使用关系运算符检查输入的字符串是否为空。

  5. 显示结果。

  6. 声明另一个字符串并将其初始化为 null。

  7. 使用关系运算符检查输入的字符串是否为空。

  8. 显示结果。

  9. 停下来。

下面的例子说明了上述算法的实现。

/*Java Program to check if a string is empty or null*/
public class Main
{  
     public static void main(String[] args) 
     {  

        String str1 = "Study Tonight"; 
        String str2 = null; 

        System.out.println("Is string:  " + str1 +"  empty or null? " + isEmptyOrNull(str1)); 
        System.out.println("Is string:  " + str2 + "  empty or null? "+ isEmptyOrNull(str2)); 

    } 
    public static boolean isEmptyOrNull(String str) 
    { 
        // use == relational operator and return the result 
        if (str == null) 
            return true; 
        else
            return false; 
    }          
} 

字符串:今晚学习是空的还是空的?false
字符串:null 是空的还是 null?真实的

程序 2:检查字符串是否为空

在这个程序中,我们将学习如何使用关系运算符或 is empty()检查字符串是空的还是 null。

算法:

  1. 开始

  2. 声明字符串

  3. 用一些值初始化它。

  4. 使用关系运算符或 isEmpty()检查输入的字符串是否为空。

  5. 显示结果。

  6. 声明另一个字符串并将其初始化为 null。

  7. 使用关系运算符或 isEmpty()检查输入的字符串是否为空。

  8. 显示结果。

  9. 停止

下面的例子说明了上述算法的实现。

/*Java Program to check if a string is empty or null*/

public class Main  
{  
     public static void main(String[] args) 
     {  
        String str1 = "Study Tonight";
        System.out.println("Entered String is: "+str1);
        System.out.println("Is the entered string empty or null? "+str1 == null || str1.isEmpty());    //false
        String str2 = ""; 
        System.out.println("Entered String is: "+str2);
        System.out.println("Is the entered string empty or null? "
        +str2 == null || str2.isEmpty());    // true

    } 
} 

输入字符串为:今晚学习

输入字符串为:

程序 3:检查字符串是否为空

在这个程序中,我们将学习如何使用 length()方法检查字符串是否为空。如果长度=0,则它是空字符串。

算法:

  1. 开始

  2. 声明字符串

  3. 用一些值初始化它。

  4. 使用 length()检查输入的字符串是否为空。

  5. 如果输入的字符串长度为 0,则为空字符串。

  6. 显示结果。

  7. 声明另一个字符串并将其初始化为 null。

  8. 使用 length()检查输入的字符串是否为空。

  9. 如果输入的字符串长度为 0,则为空字符串。

  10. 显示结果。

  11. 停止

下面的例子说明了上述算法的实现。

/*Java Program to check if a string is empty or null*/

public class Main  
{  
     public static void main(String[] args) 
     {  
        String str1 = "Study Tonight";
        System.out.println("Entered String is: "+str1);
        System.out.println("Is the entered string empty or null? " +str1 == null || str1.length() == 0);    //false
        String str2 = ""; 
        System.out.println("Entered String is: "+str2);
        System.out.println("Is the entered string empty or null? "
        +str2 == null || str2.length() == 0);    // true
    } 
} 

输入字符串为:今晚学习

输入字符串为:

程序 4:检查字符串是否为空

在这个程序中,我们将学习如何检查字符串是否为空。在这里,我们将使用。方法对空字符串进行相等性检查。

算法:

  1. 开始

  2. 声明一个字符串。

  3. 用一些值初始化它。

  4. 使用 equals()方法对空字符串进行相等性检查。

  5. 显示结果。

  6. 声明另一个字符串并将其初始化为 null。

  7. 使用 equals()方法对空字符串进行相等性检查。

  8. 显示结果。

  9. 停止

下面的例子说明了上述算法的实现。

/*Java Program to check if a string is empty or null*/

public class Main  
{  
    private static String EMPTY = "";

     public static void main(String[] args) 
     {  
        String str1 = "Study Tonight";
        System.out.println("Entered String is: "+str1);

        System.out.println("Is the entered string empty or null? ");
        System.out.println(str1 == null || EMPTY.equals(str1));    // false
        System.out.println(str1 == null || str1.equals(EMPTY));    // false

        String str2 = ""; 
        System.out.println("Entered String is: "+str2);
        System.out.println("Is the entered string empty or null? ");
        System.out.println(str2 == null || EMPTY.equals(str2));    // true
        System.out.println(str2 == null || str2.equals(EMPTY));    // true        

    } 
} 

输入的字符串是:今晚学习
输入的字符串是空的还是空的?


输入的字符串是:
输入的字符串是空的还是空的?



Java 程序:使用递归求一个数的阶乘

原文:https://www.studytonight.com/java-programs/java-program-to-find-the-factorial-of-a-number-using-recursion

在本教程中,我们将学习如何使用递归函数找到一个数的阶乘。递归函数是调用自身的函数。但是在继续之前,如果你不熟悉 java 中方法的基本概念,那么一定要查看主题为 java 中方法的文章。

**输入:**输入数字:5

**输出:**输入数字的阶乘为:120

程序 1:用递归求一个数的阶乘

在这个程序中,我们将使用带有用户定义值的递归找到一个数的阶乘。这里,我们将要求用户输入一个值,然后通过递归调用函数来计算阶乘。

算法

  1. 开始
  2. 声明一个变量来存储一个数字。
  3. 要求用户初始化数字。
  4. 检查是否可以计算阶乘。
  5. 如果数字大于等于 0,则调用递归函数来计算输入数字的阶乘。
  6. 如果数字小于 0,则打印无法计算阶乘的消息。
  7. 如果输入的数字是 0 或 1,则返回 1。
  8. 如果输入的数字不是 0 或 1,则通过递归调用相同的方法计算阶乘。
  9. 返回结果。
  10. 打印输入数字的阶乘。
  11. 停止

下面是相同的 Java 语言代码。

/*Java Program to find factorial of a number using Recursive Function*/
import java.util.Scanner;
public class Main
{
    //Driver Code
    public static void main(String[] args) 
    {
        //Take input from the user
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number :");
        int num = sc.nextInt();   //Input the number
        if(num>=0) 
        {
           //Call a recursive function to find the factorial
           int factorial=findFactorial(num);
           System.out.println("The factorial of the entered the number is :"+factorial);
        }        
        else
        {
            System.out.println("Factorial not possible.");
            System.out.println("Please enter valid input.");
        } 
    }
    //Recursive Function to Find the Factorial of a Number
    public static int findFactorial(int num)
    {
        if(num==0)
        return 1;
        else if(num==1)
        return 1;
        else
        return num*findFactorial(num-1);        
    }
}

输入数字:10
输入数字的阶乘为:3628800

程序 2:用递归求一个数的阶乘

在这个程序中,我们将使用带有预定义值的递归找到一个数的阶乘。这里,要计算阶乘的数字已经在程序中给出,我们的任务是通过递归调用函数来计算阶乘。

算法

  1. 开始
  2. 声明一个变量来存储一个数字。
  3. 初始化数字。
  4. 检查是否可以计算阶乘。
  5. 如果数字大于等于 0,则调用递归函数来计算输入数字的阶乘。
  6. 如果数字小于 0,则打印无法计算阶乘的消息。
  7. 如果输入的数字是 0 或 1,则返回 1。
  8. 如果输入的数字不是 0 或 1,则通过递归调用相同的方法计算阶乘。
  9. 返回结果。
  10. 打印输入数字的阶乘。
  11. 停止

下面是相同的 Java 语言代码。

/*Java Program to find factorial of a number using Recursive Function*/
public class Main
{
    //Driver Code
    public static void main(String[] args) 
    {
        int num=5;
        System.out.println("The entered number is :"+num);
        if(num>=0) 
        {
           //Call a recursive function to find the factorial
           int factorial=findFactorial(num);
           System.out.println("The factorial of the entered number is :"+factorial);
        }
        else
        {
            System.out.println("Factorial not possible.");
            System.out.println("Please enter valid input.");
        } 
    }
    //Recursive Function to Find the Factorial of a Number
    public static int findFactorial(int num)
    {
        if(num==0)
        return 1;
        else if(num==1)
        return 1;
        else
        return num*findFactorial(num-1);        
    }
}

输入的数字是:5
输入的数字的阶乘是:120



Java 程序:显示上三角矩阵

原文:https://www.studytonight.com/java-programs/java-program-to-display-upper-triangular-matrix

在本教程中,我们将学习如何显示上三角矩阵。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

下面是同样的图示。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

**输入:**输入矩阵元素:

1 2 3

4 5 6

7 8 9

**输出:**上三角矩阵为:

1 2 3

0 5 6

0 0 9

程序 1:显示上三角矩阵

在下面的程序中,我们将看到当值由用户定义时,如何显示上三角矩阵。在这里,我们将要求用户输入矩阵元素,然后我们将只显示那些行数大于列数的矩阵元素。

算法

  1. 开始
  2. 声明变量来存储行数和列数。
  3. 要求用户初始化行和列。
  4. 检查行数和列数是否相等。
  5. 如果不相等,则显示一条消息,说明行数和列数应该相等。
  6. 如果相等,则声明一个矩阵。
  7. 要求用户初始化矩阵元素。
  8. 打印原始矩阵。
  9. 调用一个方法来显示上三角矩阵。
  10. 使用循环迭代元素。
  11. 将 0 分配给行数大于列数的元素。
  12. 打印结果矩阵。
  13. 停下来。

下面是相同的代码。

// Java Program to print the upper triangular matrix 
import java.util.*; 
public class Main 
{ 
    // Print the matrix 
    public static void printMatrix(int[][] arr) 
    { 
        int m = arr.length;   //For Rows
        int n = arr[0].length; //For columns
        for (int i = 0; i < m; i++) 
        { 
            for (int j = 0; j < n; j++) 
            {
                System.out.print(arr[i][j] + " "); 
            }    
            System.out.println(); 
        } 
    }     
    //Display the upper triangular matrix
    public static void upperTriangularMatrix(int arr[][]) 
    { 
        int m = arr.length; 
        int n = arr[0].length;         
        if (m != n) 
        { 
            System.out.println("Matrix entered should be a Square Matrix");
            System.out.println("Try Again..");
            return; 
        } 
        else 
        { 
            // looping over the whole matrix 
            for (int i = 0; i < m; i++) 
            { 
                for (int j = 0; j < n; j++) 
                { 
                    if (i > j) 
                    { 
                        arr[i][j] = 0; 
                    } 
                } 
            }   
            System.out.println( "Upper Triangular Matrix is : ");             
            // printing the upper triangular matrix 
            printMatrix(arr); 
        } 
    } 
    public static void main(String[] args) 
    { 
        //Take input from the user
        Scanner sc=new Scanner(System.in);        
        int m,n;     //Declare variables for rows and columns
        System.out.println("Enter the number of rows: ");
        m=sc.nextInt();        
        System.out.println("Enter the number of columns: ");
        n=sc.nextInt();        
        System.out.println("Enter the matrix elements: ");
        int arr[][] = new int[m][n];   //Declare the matrix
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                arr[i][j]=sc.nextInt();   //Initialize the matrix
            }
        }
        //Print Original Matrix
        System.out.println( "Original Matrix is : "); 
        printMatrix(arr);         
        // calling to display the upper triangular matrix
        upperTriangularMatrix(arr); 
    } 
}

输入行数:3
输入列数:3
输入矩阵元素:1 2 8 7 5 4 3 9
原始矩阵为:
1 2 8
7 6 5
4 3 9
上三角矩阵为:
1 2 8
0 6 5
0 0 9

程序 2:显示上三角矩阵

在下面的程序中,我们将看到如何显示预定义值时的上三角矩阵。这里,矩阵的元素是在程序中预先定义的。因此,我们将只显示那些行数大于列数的矩阵元素。

算法

  1. 开始
  2. 声明变量来存储行数和列数。
  3. 初始化行和列。
  4. 检查行数和列数是否相等。
  5. 如果不相等,则显示一条消息,说明行数和列数应该相等。
  6. 如果相等,则声明一个矩阵。
  7. 初始化矩阵元素。
  8. 打印原始矩阵。
  9. 调用一个方法来显示上三角矩阵。
  10. 使用循环迭代元素。
  11. 将 0 分配给行数大于列数的元素。
  12. 打印结果矩阵。
  13. 停下来。

下面是相同的代码。

// Java Program to print the upper triangular matrix 
import java.io.*;   
public class Main 
{ 
    // Print the matrix 
    public static void printMatrix(int[][] arr) 
    { 
        int m = arr.length;   //For Rows
        int n = arr[0].length; //For columns
        for (int i = 0; i < m; i++) 
        { 
            for (int j = 0; j < n; j++) 
            {
                System.out.print(arr[i][j] + " "); 
            }    
            System.out.println(); 
        } 
    }     
    //Display the upper triangular matrix
    public static void upperTriangularMatrix(int arr[][]) 
    { 
        int m = arr.length; 
        int n = arr[0].length;         
        if (m != n) 
        { 
            System.out.println("Matrix entered should be a Square Matrix");
            System.out.println("Try Again..");
            return; 
        } 
        else 
        { 
            // looping over the whole matrix 
            for (int i = 0; i < m; i++) 
            { 
                for (int j = 0; j < n; j++) 
                { 
                    if (i > j) 
                    { 
                        arr[i][j] = 0; 
                    } 
                } 
            }   
            System.out.println( "Upper Triangular Matrix is : "); 

            // printing the upper triangular matrix 
            printMatrix(arr); 
        } 
    } 
    public static void main(String[] args) 
    { 
        int arr[][] = { { 8, 7, 6 }, { 4, 2, 5 }, { 7, 9, 8 } }; 
        //Print Original Matrix
        System.out.println( "Original Matrix is : "); 
        printMatrix(arr);         
        // calling to display the upper triangular matrix
        upperTriangularMatrix(arr); 
    } 
}

原矩阵为:
8 7 6
4 2 5
7 9 8
上三角矩阵为:
8 7 6
0 2 5
0 0 8



Java 程序:确定给定矩阵是否为稀疏矩阵

原文:https://www.studytonight.com/java-programs/java-program-to-determine-if-a-given-matrix-is-a-sparse-matrix

在本教程中,我们将学习如何确定给定的矩阵是否是稀疏矩阵。如果一个矩阵的大部分元素都是 0,那么这个矩阵就是稀疏矩阵。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

下面是同样的图示。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

**输入:**输入矩阵元素:

1 4 0

0 0 0

4 0 0

**输出:**是稀疏矩阵。

程序 1:确定给定的矩阵是否是稀疏矩阵

在这个程序中,我们将学习当值是用户定义的时,如何确定给定的矩阵是否是稀疏矩阵。在这里,我们将要求用户输入值,然后,我们将检查给定的矩阵是否是稀疏矩阵。

算法

  1. 开始
  2. 声明变量来存储矩阵的大小。
  3. 要求用户初始化行数和列数。
  4. 声明一个矩阵。
  5. 要求用户初始化矩阵的元素。
  6. 打印原始矩阵
  7. 声明一个变量来存储矩阵的大小。
  8. 声明一个变量来计算矩阵中 0 个元素的数量。
  9. 使用循环计算所有的零元素。
  10. 如果发现任何 0 元素,则增加计数。
  11. 检查计数是否大于大小的一半。
  12. 如果更大,则将其打印为稀疏矩阵。
  13. 否则打印它不是稀疏矩阵。
  14. 停下来。

下面是相同的代码。

//Java Program to check whether the given matrix is sparse or not*/
import java.util.Scanner; 
public class Main 
{ 
    public static void main(String[] args) 
    { 
        // declare variables 
        int m, n;  
        // To take input from the user
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter the number of rows ");   
        // Initialize the number of rows 
        m = sc.nextInt();   
        System.out.println("Enter the number of columns ");  
        // Initialize the number of columns 
        n = sc.nextInt();   
        // declare a mxn order array 
        int a[][] = new int[m][n];   
        System.out.println("Enter all the values of matrix "); 
        // Initialize the matrix elements
        for (int i = 0; i < m; i++) 
        { 
            for (int j = 0; j < n; j++) 
            { 
                a[i][j] = sc.nextInt();                 
            } 
        }    
        System.out.println("Original Matrix:"); 
        // print the original matrix 
        for (int i = 0; i < m; i++) 
        { 
            for (int j = 0; j < n; j++) 
            { 
                    System.out.print(a[i][j] + " "); 
            } 
            System.out.println(""); 
        } 
        int size= m*n;   //Stores the size of the matrix 
        int count=0;    //Variable to check for the number of 0 elements        
        //Loop to count all zero element present in matrix    
        for(int i = 0; i < m; i++)
        {    
            for(int j = 0; j < n; j++)
            {    
                if(a[i][j] == 0)    //Check if element is 0 or not
                    count++;    //Increment the count if 0 element is found
            }    
        }        
        if(count>(size/2))
        System.out.println("It is a sparse matrix");
        else
        System.out.println("It is not a sparse matrix");           
    } 
}

输入行数 3
输入列数 3
输入矩阵 1 的所有值 2 0 0 0 0 0 0
原始矩阵:
1 2 0
0 0 0
0 0 0
它是一个稀疏矩阵

程序 2:确定给定的矩阵是否是稀疏矩阵

在这个程序中,我们将学习当值被预定义时,如何确定给定的矩阵是否是稀疏矩阵。这里,矩阵的元素是在程序中预先定义的。因此,基于该矩阵的值,我们将检查给定的矩阵是否是稀疏矩阵。

算法

  1. 开始
  2. 声明并初始化矩阵。
  3. 声明变量来存储矩阵的行数和列数。
  4. 打印原始矩阵。
  5. 声明一个变量来存储矩阵的大小。
  6. 声明一个变量来计算矩阵中 0 个元素的数量。
  7. 使用循环计算所有的零元素。
  8. 如果发现任何 0 元素,则增加计数。
  9. 检查计数是否大于大小的一半。
  10. 如果更大,则将其打印为稀疏矩阵。
  11. 否则打印它不是稀疏矩阵。
  12. 停下来。

下面是相同的代码。

//Java Program to check whether the given matrix is sparse or not*/
public class Main 
{ 
    public static void main(String[] args) 
    {         
        // declare and initialize a matrix 
        int a[][] = {{ 2, 9, 8 }, { 7, 6, 4 }, { 3, 9, 2 } };   
        int m=a.length;   //Stores the number of rows in a matrix
        int n=a[0].length;   //Stores the number of columns in a matrix 
         // print the original matrix 
        System.out.println("Original Matrix:"); 
        for (int i = 0; i < m; i++) 
        { 
            for (int j = 0; j < n; j++) 
            { 
                    System.out.print(a[i][j] + " "); 
            } 
            System.out.println(""); 
        }   
        int size= m*n;   //Stores the size of the matrix        
        int count=0;    //Variable to check for the number of 0 elements        
        //Loop to count all zero element present in matrix    
        for(int i = 0; i < m; i++)
        {    
            for(int j = 0; j < n; j++)
            {    
                if(a[i][j] == 0)    //Check if element is 0 or not
                    count++;    //Increment the count if 0 element is found            }    
        }        
        if(count>(size/2))
        System.out.println("It is a sparse matrix");
        else
        System.out.println("It is not a sparse matrix");           
    } 
}

原始矩阵:
2 9 8
7 6 4
3 9 2
它不是稀疏矩阵



Java 程序:接受M*N阶矩阵并交换对角线

原文:https://www.studytonight.com/java-programs/java-program-to-accept-a-matrix-of-order-mn-and-interchange-the-diagonals

在本教程中,我们将学习如何接受 M*N 阶的矩阵并交换对角线。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

**输入:**输入矩阵元素:

1 2 3

6 5 4

7 8 9

输出:

3 2 1

4 5 6

9 8 7

程序 1:交换矩阵的对角线

在这个程序中,我们将看到如何接受 M*N 阶的矩阵,并用用户定义的值交换对角线。

算法

  1. 开始
  2. 声明矩阵大小的变量。
  3. 要求用户初始化矩阵行和列
  4. 检查行数和列数是否相等。
  5. 如果相等,则要求用户初始化矩阵。
  6. 打印原始矩阵。
  7. 交换对角线元素。
  8. 打印互换的矩阵。
  9. 如果行和列不相等,则打印相同的消息。
  10. 停止

下面是相同的代码。

//Java Program to interchange the diagonals*/
import java.util.Scanner; 

public class Main 
{ 
    public static void main(String[] args) 
    { 
        // declare variables 
        int m, n, temp; 

        // To take input from the user
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter number of rows "); 

        // Initialize the number of rows 
        m = sc.nextInt(); 

        System.out.println("Enter number of columns "); 

        // Initialize the number of columns 
        n = sc.nextInt(); 

        // declare a mxn order array 
        int a[][] = new int[m][n]; 

        // Interchange the diagonals only when it is a square matrix
        if (m == n) 
        { 
            System.out.println("Enter all the values of matrix "); 

            // Initialize the matrix elements
            for (int i = 0; i < m; i++) 
            { 
                for (int j = 0; j < n; j++) 
                { 
                    a[i][j] = sc.nextInt(); 
                } 
            } 

            System.out.println("Original Matrix:"); 

            // print the original matrix 
            for (int i = 0; i < m; i++) { 
                for (int j = 0; j < n; j++) { 
                    System.out.print(a[i][j] + " "); 
                } 
                System.out.println(""); 
            } 

            // Interchange the diagonals by swapping 
            for (int j = 0; j < m; j++) 
            { 
                temp = a[j][j]; 
                a[j][j] = a[j][n - 1 - j]; 
                a[j][n - 1 - j] = temp; 
            } 
            System.out.println("After interchanging diagonals of matrix "); 

            // print interchanged matrix 
            for (int i = 0; i < m; i++) { 
                for (int j = 0; j < n; j++) { 
                    System.out.print(a[i][j] + " "); 
                } 
                System.out.println(""); 
            } 
        }       
        else 
        { 
            System.out.println("Rows not equal to columns"); 
        } 
    } 
}

输入行数 3
输入列数 3
交换矩阵对角线后输入矩阵 1 2 3 4 5 6 7 8 9
原始矩阵:
1 2 3
4 5 6
7 8 9
交换矩阵对角线后
3 2 1
4 5 6
9 8 7

程序 2:交换矩阵的对角线

在这个程序中,我们将看到如何接受 M*N 阶的矩阵,并将对角线与预定义的值互换。

算法

  1. 开始
  2. 声明并初始化矩阵大小。
  3. 检查行数和列数是否相等。
  4. 如果相等,则初始化矩阵的元素。
  5. 打印原始矩阵。
  6. 调用一个方法来交换对角线。
  7. 交换对角线元素。
  8. 打印互换的矩阵。
  9. 如果行和列不相等,则打印相同的消息。
  10. 停止

下面是相同的代码。

//Java Program to interchange the diagonals*/
import java.util.*; 

public class Main 
{ 
    //Method to interchange the diagonals
    static void interchangeDiagonals(int arr[][])
    {
        int temp=0;   
        int m=arr.length;     //Variable to store the number of rows
        int n=arr[0].length;  //Variable to store the number of columns
         System.out.println("Original Matrix:"); 

            // print the original matrix 
            for (int i = 0; i < m; i++) 
            { 
                for (int j = 0; j < n; j++) 
                { 
                    System.out.print(arr[i][j] + " "); 
                } 
                System.out.println(""); 
            } 

            // Interchange the diagonals by swapping 
            for (int j = 0; j <m; j++) 
            { 
                temp = arr[j][j]; 
                arr[j][j] = arr[j][n - 1 - j]; 
                arr[j][n - 1 - j] = temp; 
            } 
            System.out.println("After interchanging diagonals of matrix "); 

            // print interchanged matrix 
            for (int i = 0; i < m; i++) { 
                for (int j = 0; j < n; j++) { 
                    System.out.print(arr[i][j] + " "); 
                } 
                System.out.println(""); 
            }    
    }
    public static void main(String[] args) 
    { 
        // declare variables 
        int rows=3, columns=3; 
        // Interchange the diagonals only when it is a square matrix
        if (rows == columns) 
        { 
           int arr[][]  = { { 2, 9, 8 }, { 7, 6, 4 }, { 3, 9, 2 } };   //Matrix Declaration
           interchangeDiagonals(arr);
        }
        else 
        { 
            System.out.println("Rows not equal to columns"); 
        } 
    } 
}

原始矩阵:
2 9 8
7 6 4
3 9 2
交换矩阵对角线后
8 9 2
7 6 4
2 9 3



Java 程序:计算给定矩阵的迹和范数

原文:https://www.studytonight.com/java-programs/java-program-to-find-the-trace-and-normal-of-a-given-matrix

在本教程中,我们将学习如何找到矩阵的迹和范数。矩阵中的迹定义为对角元素的和,范数定义为矩阵元素平方和的平方根。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

下面是如何找到矩阵轨迹的图示。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

下面是如何求矩阵范数的图示。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

**输入:**输入矩阵元素:5 4 3 1 2 6 9 8 7

**输出:**矩阵的轨迹为:14.0

矩阵的范数为:16.88

程序 1:寻找矩阵的迹和范数

在这个程序中,我们将看到当值是用户定义的时,如何找到矩阵的迹和范数。

算法

  1. 开始
  2. 为行和列声明变量。
  3. 要求用户初始化行和列。
  4. 声明一个矩阵。
  5. 要求用户初始化矩阵元素。
  6. 打印原始矩阵。
  7. 声明两个变量来计算矩阵的迹和范数。
  8. 将这些变量初始化为零。
  9. 使用两个 for 循环来计算矩阵的轨迹。
  10. 使用第一个 for 循环遍历行。
  11. 使用第二个 for 循环遍历列。
  12. 使用 if 条件检查行号和列号是否相同。
  13. 如果相同,则计算每次迭代中的跟踪。
  14. 打印矩阵的跟踪值。
  15. 现在,要再次计算矩阵的范数,循环使用两个。
  16. 使用第一个 for 循环遍历行。
  17. 使用第二个 for 循环遍历列。
  18. 计算每个数字的平方,并在每次迭代中更新平方变量。
  19. 现在,求上面计算的平方的平方根。
  20. 打印结果。
  21. 停止

下面的程序演示了如何找到矩阵的迹和范数。

/*JAVA PROGRAM TO FIND THE TRACE AND NORMAL OF A MATRIX*/
import java.util.*;
public class Main
{
     public static void main(String []args)
     {
         ///Take input from the user
         Scanner sc=new Scanner(System.in);        
         int m,n;                 //Matrix Row and Column Declaration        
         System.out.println("Enter the number of rows: \n");
         m=sc.nextInt();  //Matrix Row Initialization        
         System.out.println("Enter the number of column: \n");
         n=sc.nextInt();  //Matrix Column Initialization        
         int arr[][]=new int[10][10];        //Matrix Size Declaration        
         System.out.println("Enter the elements of the matrix: ");
         for(int i=0;i<m;i++)    //Matrix Elements Initialization
         {
            for(int j=0;j<n;j++)
            {
                 arr[i][j]=sc.nextInt();
            }
         }        
         //Print the original Matrix
         System.out.println("The elements in the original matrix are: ");
         for(int i=0;i<m;i++)     
         {
             for(int j=0;j<n;j++)
             {
                  System.out.print(arr[i][j]+" "); //Print the matrix elements
             }
            System.out.println("");
        }       
        double sum=0;        //Declare and initialize the trace variable
        double square=0;     //Declare and initialize the normal variable       
        //Find the trace of the matrix
        System.out.println("The Trace of the above matrix is ");
  	    for(int i = 0; i < m; i++)
  	    {  
    	    for(int j = 0; j < n; j++)
       	    {
                if(i == j)
            	 {
               	     sum = sum + (arr[i][j]);      //Calculate the trace in each iteration
               	 }
            }
        }
        System.out.println(sum);  //Print the trace of the matrix       
        //Find the normal of the matrix
        System.out.println("The Normal of the above matrix is "); 
   	    for(int i = 0; i < m; i++)
   	    {
    	    for(int j = 0; j < n; j++)
       	    {
       	        square = square + (arr[i][j])*(arr[i][j]);     //Calculate the normal in each iteration
            }
    	}
        double result = Math.sqrt(square);
        System.out.println(result);     //Print the normal       
     }
}

输入行数:3
输入列数:3
输入矩阵的元素:1 2 3 4 5 6 7 8 9
原矩阵中的元素为:
1 2 3
4 5 6
7 8 9
上述矩阵的迹为
15.0
上述矩阵的范数为
16.881943016134134

程序 2:寻找矩阵的迹和范数

在这个程序中,我们将看到当值被预定义时,如何找到矩阵的迹和范数。

算法

  1. 开始
  2. 声明并初始化矩阵。
  3. 打印原始矩阵。
  4. 调用一个方法来计算矩阵的轨迹。
  5. 在该方法中声明一个变量和,并将其初始化为 0。
  6. 当对角线值遇到时,增加总和。
  7. 显示总和。
  8. 现在,调用一个方法来计算矩阵的范数。
  9. 声明一个变量 square 并将其初始化为 0。
  10. 计算每个数字的平方,并在每次迭代中更新平方变量。
  11. 现在,求上面计算的平方的平方根。
  12. 打印结果。
  13. 停止

下面的程序演示了如何找到矩阵的迹和范数。

/*Java Program to find the trace and normal of a matrix*/
import java.io.*; 
public class Main 
{   
    //To Find the normal of a matrix 
    public static void findNormal(int[][] arr) 
    { 
         double square = 0, result = 0;
        System.out.println("The Normal of the above matrix is "); 
   	for(int i = 0; i < arr.length; i++)
   	{
    	    for(int j = 0; j < arr[0].length; j++)
       	    {
       	        square = square + (arr[i][j])*(arr[i][j]);
            }
    	}
        result = Math.sqrt(square);
        System.out.println(result);
    }     
    //To Find the trace of a matrix 
    public static void findTrace(int[][] arr) 
    { 
        double sum = 0;
        System.out.println("The Trace of the above matrix is ");
  	for(int i = 0; i < arr.length; i++)
  	{  
    	    for(int j = 0; j < arr[0].length; j++)
       	    {
                if(i == j)
            	 {
               	     sum = sum + (arr[i][j]);
               	 }
            }
        }
        System.out.println(sum);          
    }    
    // Driver code 
    public static void main(String args[]) throws IOException 
    { 
        int arr[][] 
            = { { 2, 9, 8 }, { 7, 6, 4 }, { 3, 9, 2 } };  //Matrix Declaration and Initialization
            System.out.println("Original Matrix");
       for(int i = 0; i < arr.length; i++)
  	   {  
    	    for(int j = 0; j < arr[0].length; j++)
       	    {
                System.out.print(arr[i][j]+ " ");
            }
            System.out.println();
        }
        System.out.println();
        findTrace(arr);    //Find the Trace of the Matrix
        System.out.println();
        findNormal(arr);   //Find the Normal of the Matrix                  
    } 
} 

原始矩阵
2 9 8
7 6 4
3 9 2
T5】上述矩阵的迹为
10.0

上述矩阵的范数为
18 . 36960 . 499999999606



Java 程序:计算单利

原文:https://www.studytonight.com/java-programs/java-program-to-find-simple-interest

在本教程中,我们将学习如何在给定本金、利率和时间段的情况下找到单利。简单利息是计算贷款利息费用最简单的方法。但是在继续之前,如果你不熟悉 java 中算术运算符的概念,那么一定要查看关于 Java 中运算符的文章。

**输入:**输入本金金额:6200

输入汇率:11

输入时间段:2

输出:

单利:1364.0

程序 1:找到对 Java 的单利

在这个程序中,我们将看到当值是用户定义的时,如何使用公式找到简单的兴趣。这意味着,首先我们将要求用户初始化变量,然后我们将使用公式找到简单的兴趣。

算法:

  1. 开始

  2. 创建 Scanner 类的实例,从用户处获取输入。

  3. 为本金、利率和时间段声明变量。

  4. 要求用户初始化这些变量。

  5. 用公式计算单利。

  6. 打印简单利息的值。

  7. 停止

下面是寻找单利的 Java 代码。

//Java Program to find the simple interest
import java.util.Scanner;
public class Main
{
    public static void main(String args[]) 
    {
        //Take input from the user
        //Create an instance of Scanner class
        Scanner sc = new Scanner(System.in);
        //Declare variables
        float p, r, t, si;
        System.out.println("Enter the Principal : ");
        p = sc.nextFloat();     //Initialize the variables
        System.out.println("Enter the Rate of interest : ");
        r = sc.nextFloat();     //Initialize the variables
        System.out.println("Enter the Time period : ");
        t = sc.nextFloat();     //Initialize the variables
        sc.close();
        //Calculate the simple interest
        si = (p * r * t) / 100;
        //Print the simple interest
        System.out.println("Simple Interest is: " +si);
    }
} 

输入本金:2000
输入利率:5
输入时间段:2
单利为:200.0

程序 2:找到对 Java 的单利

在这个程序中,我们将找到本金、利率和预定义值的时间段。

算法:

  1. 开始

  2. 声明本金、利率和时间段的变量。

  3. 初始化变量。

  4. 用公式计算单利。

  5. 打印简单利息。

  6. 停止

下面是寻找单利的 Java 代码。

//Java Program to find the simple interest
import java.util.Scanner;
public class Main
{
    public static void main(String args[]) 
    {
        //Declare and Initialize the Principle, Rate and Time Period
        float P = 1500, R = 10, T = 2; 
        System.out.println("The entered principle amount is = " + P);
        System.out.println("The entered rate is = " + R);
        System.out.println("The entered time period is " + T);

        // Calculate simple interest 
        float SI = (P * T * R) / 100;
        //Print the simple interest 
        System.out.println("Simple interest = " + SI);  
    }
} 

录入本金金额= 1500.0
录入利率= 10.0
录入时间段为 2.0
单利= 300.0

程序 3:找到对 Java 的单利

在这个程序中,我们将通过使用用户定义的函数来找到本金、利率和时间段。这里,我们将使用用户定义的函数来计算简单利息。

算法:

  1. 开始

  2. 创建 Scanner 类的实例,从用户处获取输入。

  3. 为本金、利率和时间段声明变量。

  4. 要求用户初始化这些变量。

  5. 调用一个方法来计算单利。

  6. 用公式计算单利。

  7. 打印简单利息的值。

  8. 停止

下面是寻找单利的 Java 代码。

//Java Program to find the simple interest
import java.util.Scanner;
public class Main
{
    //User-defined program to find the simple interest
    public static float simpleInterest(float principal, float rate, float time)
    {
        float interest = (principal*rate*time)/100;
        return interest;
    }

    public static void main(String args[]) 
    {
        //Take input from the user
        //Create an instance of Scanner class
        Scanner sc = new Scanner(System.in);
        //Declare variables
        float p, r, t;
        System.out.println("Enter the Principal : ");
        p = sc.nextFloat();     //Initialize the variables
        System.out.println("Enter the Rate of interest : ");
        r = sc.nextFloat();     //Initialize the variables
        System.out.println("Enter the Time period : ");
        t = sc.nextFloat();     //Initialize the variables
        sc.close();

        //Call a method to calculate the simple interest
        float interest = simpleInterest(p,r,t);
        System.out.println("Simple interest is : " + interest);

    }

} 

输入本金:4500
输入利率:12
输入时间段:3
单利为:1620.0



Java 程序:分离左侧的 0 和右侧的 1

原文:https://www.studytonight.com/java-programs/program-to-separate-0s-on-the-left-side-and-1s-on-the-right-side

在本教程中,我们将学习如何将数组左侧的 0 和右侧的 1 分开。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

**输入:**0 0 1 0 1 0 1 1 0 1 1 1

**输出:**0 0 0 1 1 1 1 1 1 1

程序 1:左边分开 0,右边分开 1

在这个方法中,我们将看到如何使用排序技术将数组左侧的 0 和右侧的 1 分开。

算法

  1. 开始
  2. 声明数组大小。
  3. 要求用户初始化数组大小。
  4. 声明数组。
  5. 要求用户初始化数组元素。
  6. 检查输入的元素是否为 0 和 1。
  7. 如果输入的元素不是 0 和 1,请用户再次输入。
  8. 如果输入的元素是 0 和 1,则使用 arrays.sort()对数组进行排序
  9. 这种排序将保持 0 在左侧,1 在右侧。
  10. 打印排序后的数组。
  11. 停下来。

下面的程序演示了如何使用排序技术将数组左侧的 0 和右侧的 1 分开。

import java.util.*;  
import java.util.Arrays; 
//Driver Code
public class Main  
{  
    static void printElements(int arr[],int n)
    {
        System.out.println("Resultant Array is ");
        for(int i=0;i<n;i++)
        {
            System.out.print(arr[i]+" ");
        }
        System.out.println(" ");
    }
   public static void main(String args[])   
   {  
       Scanner sc=new Scanner(System.in);
      int n;    //Declare array size
      System.out.println("Enter the total number of elements ");
      n=sc.nextInt();     //Initialize array size
      int arr[]=new int[n];   //Declare array
      System.out.println("Enter the elements of the array ");
      for(int i=0; i<n ;i++)     //Initialize array
      {
          arr[i]=sc.nextInt();
      }      
      int flag=1;      
        for(int t=0;t<n;t++)
        {
            if(arr[t]==0 || arr[t]==1)
            {
               Arrays.sort(arr);     //Sort the array
               flag++;
           }
          else
          {
                 flag=0;
          }
      }      
      if(flag==0)
      {
          System.out.println("Elements other than 0 and 1 are entered");
          System.out.println("Please Enter Valid Inputs ");
      }
      else{
          printElements(arr,n);
      }                 
   }
}

输入元素总数 10
输入数组的元素 0 0 1 1 1 0 0 0
结果数组是
0 0 0 1 1 1 1

程序 2:左边分开 0,右边分开 1

在这个方法中,我们将看到如何使用分离技术来分离数组左侧的 0 和右侧的 1。

算法

  1. 开始
  2. 声明数组大小。
  3. 要求用户初始化数组大小。
  4. 声明数组。
  5. 要求用户初始化数组元素。
  6. 首先检查输入的元素是否为 0 和 1。
  7. 如果输入的元素不是 0 和 1,请用户再次输入。
  8. 如果输入的元素是 0 和 1,则声明一个变量来计算零的总数。
  9. 使用 for 循环迭代数组的每个元素。
  10. 在发现 0 的地方增加计数。
  11. 现在,用 0 填充循环直到计数。
  12. 用 1 填充数组的剩余元素。
  13. 停止

下面的程序演示了如何使用分离技术分离数组左侧的 0 和右侧的 1。

import java.util.*;  
import java.util.Arrays; 

//Driver Code
public class Main  
{  
    static void printElements(int arr[],int n)
    {
        System.out.println("Resultant Array is ");
        for(int i=0;i<n;i++)
        {
            System.out.print(arr[i]+" ");
        }
        System.out.println(" ");
    }
   public static void main(String args[])   
   {  
       Scanner sc=new Scanner(System.in);

      int n;    //Declare array size
      System.out.println("Enter the total number of elements ");
      n=sc.nextInt();     //Initialize array size

      int arr[]=new int[n];   //Declare array
      System.out.println("Enter the elements of the array ");
      for(int i=0; i<n ;i++)     //Initialize array
      {
          arr[i]=sc.nextInt();
      }

      int flag=1;

        for(int t=0;t<n;t++)
        {
            if(arr[t]==0 || arr[t]==1)
            {
               // Counts the no of zeros in array 
               int count = 0; 

               // Iteration over each element of the array 
               for (int i = 0; i < n; i++) 
               { 
                    if (arr[i] == 0) 
                    count++;       // Incrementing the count 
               } 

             // Loop to fill the array with 0 until count 
             for (int i = 0; i < count; i++) 
             arr[i] = 0; 

             // Loop to fill the remaining array space with 1 
             for (int i = count; i < n; i++) 
                arr[i] = 1; 

           flag++;
          }
          else
          {
                 flag=0;
          }
      }

      if(flag==0)
      {
          System.out.println("Elements other than 0 and 1 are entered");
          System.out.println("Please Enter Valid Inputs ");
      }
      else
      {
          printElements(arr,n);
      }

   }
}

输入元素总数 10
输入数组的元素 0 0 1 1 0 1 1 0 0
结果数组是
0 0 0 1 1 1 1



基本程序

Java 程序:使用递归打印整数的二进制表示

原文:https://www.studytonight.com/java-programs/java-program-to-print-binary-equivalent-of-an-integer-using-recursion

在本教程中,我们将学习如何使用递归打印整数的二进制表示。递归函数是调用自身的函数。但是在进一步讨论之前,如果您不熟悉 java 中 if 语句的概念,那么一定要查看主题为 Java 中条件语句的文章。

**输入:**输入数字:7

**输出:**等效二进制数为 111

程序 1:使用递归打印整数的二进制表示

在这个程序中,我们将看到如何使用递归打印整数的二进制表示。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明一个变量来存储数字。
  4. 要求用户初始化数字。
  5. 把这个数除以 2。
  6. 当数除以 2 时,存储余数。
  7. 重复以上两个步骤,直到数字大于零。
  8. 以相反的顺序打印数字。
  9. 停下来。

让我们看看下面的例子,以更好地理解上述算法。

//Java Program to convert an integer to binary
import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        int n;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        n = sc.nextInt();
        Main obj = new Main();
        int m = obj.binary(n);
        System.out.println("The binary equivalent is:"+m);
    }
   public static int binary(int n)
    {
        if (n == 1) 
        {
            return 1;
        }
        return binary(n / 2) * 10 + n % 2;
    }
}

输入数字:9
二进制等值为:1001

程序 2:使用递归打印整数的二进制表示

在这个程序中,我们将看到如何使用递归打印整数的二进制表示。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明一个变量来存储数字。
  4. 要求用户初始化数字。
  5. 声明一个静态方法,该方法采用一个整数参数作为参数并返回一个字符串。
  6. 使用 StringBuilder 类将结果相互追加,并使用 toString()方法将输出生成器对象转换为字符串。
  7. 将特定数字除以 2,并将余数存储在变量中。
  8. 存储数字除以 2 后的整数值。
  9. 再次调用该函数,并用余数追加其结果
  10. 满足基本条件(number == 0)后,它从方法返回 StringBuilder 对象。
  11. 打印结果。
  12. 停下来。

让我们看看下面的例子,以更好地理解上述算法。

//Java Program to convert an integer to binary
import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        int n;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        n = sc.nextInt();
        Main obj = new Main();
        String m = obj.BRec(n);
        System.out.println("The binary equivalent is:"+m);
    }
    public static String BRec(int num)
    {
    	StringBuilder sB = new StringBuilder();  
        if(num > 0)
        {
            //get the remainder of the number when divided with 2
            int rem = num % 2;
            //get the whole number after the division
            num /=  2;
            sB.append(BRec(num)).append("").append(String.valueOf(rem));
            return sB.toString();
        }
        else 
        {
           return sB.toString();
        }
     }

}

输入数字:9
二进制等值为:1001



Java 程序:不使用递归将二进制数转换为格雷码

原文:https://www.studytonight.com/java-programs/java-program-to-convert-binary-code-into-gray-code-without-using-recursion

在本教程中,我们将学习如何在不使用递归的情况下将数字的二进制数转换为其等效的格雷代码。格雷码是一种二进制数字系统,其中两个连续值仅相差一位。但是在继续之前,如果你不熟悉 java 中方法的基本概念,那么一定要查看主题为 java 中方法的文章。

**输入:**输入二进制数:1110

**输出:**等效格雷码为:1001

让我们看看例子,以便更好地理解。

程序 1:不使用递归将一个数的二进制码转换成它的等价格雷码

在这个例子中,我们将看到如何在不使用递归的情况下将数字的二进制数转换成它的等价格雷码。

算法:

  1. 开始
  2. 创建扫描仪类的实例。
  3. 声明一个变量来存储二进制数。
  4. 要求用户初始化变量。
  5. 声明一个用户定义的方法来将二进制数转换为格雷码。
  6. 遍历字符串的所有位。
  7. 对二进制字符串的前一位和当前位执行异或运算。
  8. 重复这个过程,直到字符串的所有位都被覆盖。
  9. 打印结果。
  10. 停下来。

下面的例子说明了上述算法的实现。

//Java Program to Convert Binary Code Into 
//Equivalent Gray Code Without Using Recursion
import java.util.*;

public class Main 
{
  public static void toGray(String str)
    {
        // a String varaible to store the obtained gray string.
        String gray = new String();
        gray += str.charAt(0);
        for (int i = 1; i < str.length(); i++)
        {
            // perform XOR on the prevous bit and the
            // current bit of the binary string
         gray += (Integer.parseInt(String.valueOf(str.charAt(i - 1))) ^ 
                   Integer.parseInt(String.valueOf(str.charAt(i))));

        }
        System.out.println("The equivalent gray code is : " + gray);
    }

    // Driver Program
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Binary number:");
        String str = sc.nextLine();
        toGray(str);
    }
}

输入二进制数:111011001
等效的格雷码为:100110101

程序 2:不使用递归将一个数的二进制码转换成它的等价格雷码

在这个例子中,我们将看到如何在不使用递归的情况下将数字的二进制数转换成它的等价格雷码。

算法:

  1. 开始
  2. 创建扫描仪类的实例。
  3. 声明一个变量来存储二进制数。
  4. 要求用户初始化变量。
  5. 声明一个用户定义的方法来将二进制数转换为格雷码。
  6. 首先,遍历字符串的所有字符。
  7. 声明另一个单独的用户定义函数,该函数将返回两个数字的异或。
  8. 重复这些步骤,直到找到字符串所有位的 xor 值。
  9. 显示输出。
  10. 停下来。

下面的例子说明了上述算法的实现。

//Java Program to Convert Binary Code Into 
//Equivalent Gray Code Without Using Recursion
import java.util.*;

public class Main 
{
    public static int xOR(char a, char b)
    {
        // return 1 if both bits are not same
        if (a != b)
            return 1;

        // else return 0
        return 0;
    }
    // converts the given binary string into its equivalent gray code
    public static void toGray(String str)
    {
        String gray = new String();
        gray += str.charAt(0);
        // for all the other bits, traverse through the
        // binary string
        for (int i = 1; i < str.length(); i++)
        {
            // calling xOR() method on the prevous bit and
            // the current bit of the binary string
            gray += xOR(str.charAt(i - 1), str.charAt(i));
        }
        System.out.println("The equivalent gray code is : " + gray);
    }
    // Driver Program
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Binary number:");
        String str = sc.nextLine();
        toGray(str);
    }
}

输入二进制数:100011001
等效的格雷码为:110010101



Java 程序:使用递归求数字和

原文:https://www.studytonight.com/java-programs/java-program-to-find-sum-of-digits-of-a-number-using-recursion

在本教程中,我们将学习如何使用递归找到一个数字的所有数字的总和。递归函数是重复调用自身的函数。在这里,我们将首先要求用户初始化数字,然后通过递归调用函数来找到所有的数字并计算它们的总和。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。

**输入:**输入数字:564

**输出:**所有数字之和为:15

让我们看看例子,了解如何用递归求数字的和。

程序 1:一个数字的数字总和

在下面的例子中,我们将看到如何使用递归来求一个数的位数之和。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明一个变量来存储数字。
  4. 要求用户初始化变量。
  5. 声明一个用户定义的函数,使用递归计算数字的位数总和。
  6. 递归调用函数来计算数字的总和。
  7. 显示数字的总和。
  8. 停下来。

下面的例子说明了上述算法的实现。

//Java Program to find the sum of digits using recursion
import java.util.*;

public class Main 
{
    public static int sum_of_digit(int num)
    { 
        if (num == 0)
            return 0;
        return (num % 10 + sum_of_digit(num / 10));
    }
    // Driver Program
    public static void main(String args[])
    {
        //Take input from the user
        //Create an instance of the Scanner Class
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number: ");
        int num=sc.nextInt();
        int res=sum_of_digit(num);
        System.out.println("The sum of digits is: "+res);
    }
}

输入数字 854
该数字的位数总和为 17

程序 2:一个数字的数字总和

在下面的例子中,我们将看到如何使用递归来求一个数的位数之和。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明一个变量来存储数字。
  4. 要求用户初始化变量。
  5. 声明一个用户定义的函数,使用递归计算数字的位数总和。
  6. 递归调用函数来计算数字的总和。
  7. 返回计算出的总和。
  8. 打印结果。
  9. 停下来。

下面的例子说明了上述算法的实现。

//Java Program to find the sum of digits using recursion
import java.util.*;

public class Main 
{
	int sum=0;
	int sumOfDigits(long num)
	{
	   if(num!=0)
	    {
	     	sum+=num%10;
	    	num/=10;
		    sumOfDigits(num);
	    }
	return sum;
	}
    //Driver code
	public static void main(String arg[])	
	{
	    long num,res;
	    Main main=new Main();
	    //Take input from the user
	    //Create an instance of the Scanner class
        Scanner sc=new Scanner(System.in);
	    System.out.println("Enter a number ");
        num=sc.nextLong();
	    System.out.println("The sum of digits of the number is "+main.sumOfDigits(num));

	}
}

输入一个数字 4567854
这个数字的位数总和是 39



Java 程序:使用方法重载求正方形、矩形和圆形面积

原文:https://www.studytonight.com/java-programs/java-program-to-find-area-of-square-rectangle-and-circle-using-method-overloading

在本教程中,我们将学习如何使用方法重载来查找正方形、矩形和圆形的面积。矩形的面积是它的长度和宽度的乘积。圆的面积是圆半径的平方和圆周率的乘积。正方形的面积是它的边的平方。如果一个类有多个同名但参数不同的方法,称为方法重载。但是在继续之前,如果你不熟悉 java 中方法重载的概念,那么一定要检查一下 Java 中的方法重载

**输入:**区域(3)

面积(3,2)

区域(3.2)

输出:

这个广场的面积是 9 平方。单位。

这个长方形的面积是 6 平方。单位。

这个圆的面积是 32.15 平方。单位。

让我们看看下面的例子,以便更好地理解。

Java 程序:程序 1:使用方法重载寻找正方形、矩形和圆形区域

在这个程序中,我们将看到如何使用方法重载来找到正方形、矩形和圆形的面积。

算法:

  1. 开始
  2. 为矩形、正方形和圆形声明三个不同的类。
  3. 声明两个同名但具有不同数量参数或不同数据类型的方法。
  4. 使用对象调用这些方法。
  5. 根据参数数量或数据类型调用相应的方法。
  6. 显示结果。
  7. 停下来。

让我们看看下面的例子,以更好地理解上述算法。

//Java Program to Find the Area of Square, Rectangle and Circle using Method Overloading
public class Main 
{
    //Driver Code
    public static void main(String[] args)
    {
        Rectangle obj = new Rectangle();
        // Calling function
        obj.Area(30, 20);
        obj.Area(12.5, 4.5);
        Circle obj1 = new Circle();
        // Calling function
        obj1.Area(3);
        obj1.Area(5.5);
        Square obj2 = new Square();
        // Calling function
        obj2.Area(20);
        obj2.Area(5.2);

    }
}
class Square 
{
    // Overloaded function to
    // calculate the area of the square
    // It takes one double parameter
    void Area(double side)
    {
        System.out.println("Area of the Square: "+ side * side);
    }
    // Overloaded function to
    // calculate the area of the square
    // It takes one float parameter
    void Area(float side)
    {
        System.out.println("Area of the Square: "+ side * side);
    }
}
class Circle 
{
    static final double PI = Math.PI;

    // Overloaded function to
    // calculate the area of the circle.
    // It takes one double parameter
    void Area(double r)
    {
        double A = PI * r * r;

        System.out.println("The area of the circle is :" + A);
    }

    // Overloaded function to
    // calculate the area of the circle.
    // It takes one float parameter
    void Area(float r)
    {
        double A = PI * r * r;

        System.out.println("The area of the circle is :" + A);
    }
}
class Rectangle 
{
     // Overloaded function to
    // calculate the area of the rectangle
    // It takes two double parameters
    void Area(double l, double b)
    {
        System.out.println("Area of the rectangle: " + l * b);
    }
    // Overloaded function to
    // calculate the area of the rectangle.
    // It takes two float parameters
    void Area(int l, int b)
    {
        System.out.println("Area of the rectangle: " + l * b);
    }
}

矩形面积:600
矩形面积:56.25
圆面积:28.274333882308138
圆面积:95.03317777109123
广场面积:400.0
广场面积:27.040000000000003

程序 2: Java 程序使用方法重载寻找正方形、矩形和圆形的面积

在这个程序中,我们将看到如何使用方法重载来找到正方形、矩形和圆形的面积。

算法:

  1. 开始
  2. 用不同数量的参数或不同的数据类型声明三个同名的方法。
  3. 使用对象调用这些方法。
  4. 根据参数数量或数据类型调用相应的方法。
  5. 显示结果。
  6. 停下来。

让我们看看下面的例子,以更好地理解上述算法。

//Java Program to Find the area of Square, Rectangle and Circle using Method Overloading
public class Main 
{
    //Driver Code
    public static void main(String[] args)
    {
       CalculateArea ob = new CalculateArea();
	   ob.area(4);
	   ob.area(10,12);
	   ob.area(5.5);
    }
}
class CalculateArea
{
    void area(float x)
    {
        System.out.println("The area of the square is "+Math.pow(x, 2)+" sq units");
    }
    void area(float x, float y)
    {
        System.out.println("The area of the rectangle is "+x*y+" sq units");
    }
    void area(double x)
    {
        double z = 3.14 * x * x;
        System.out.println("The area of the circle is "+z+" sq units");
    }
}

正方形的面积是 16.0 平方米
长方形的面积是 120.0 平方米
圆形的面积是 94.985 平方米



Java 程序:计算梯形面积

原文:https://www.studytonight.com/java-programs/java-program-to-find-the-area-of-a-trapezium

在本教程中,我们将学习如何在 java 中计算梯形的面积。梯形是 2D 形状,属于有一对平行边的四边形的范畴。梯形面积是二维平面中由梯形覆盖的区域。但是在继续之前,如果你不熟悉数据类型的概念,那么一定要查看关于 Java 中数据类型的文章

**输入:**输入梯形平行边的长度:5

输入梯形平行边的长度:3

输入梯形的高度:4

**输出:**梯形的面积:16

下面是同样的图示。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

上述问题出现了两种情况:

情况 1:当给定平行边和高度时

案例二:当所有的边都给了。

让我们分别看看这些案例。

Java 程序:程序 1:寻找梯形面积

在这个程序中,我们将学习如何使用底部和高度公式来寻找梯形的面积。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明变量来存储梯形边的值。
  4. 要求用户初始化变量。
  5. 声明另一个变量来存储梯形的高度。
  6. 使用底部和高度公式计算面积。
  7. 显示结果。
  8. 停下来。

下面的程序演示了如何找到梯形的面积。

//Java Program to Calculate the Area of a Trapezium
import java.util.Scanner;
public class Main
{
     public static void main(String []args)
     {
        //Take input from the user 
        //Create an instance of the Scanner Class
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the length of the parallel sides of the trapezium: ");
        double side1=sc.nextDouble();
        System.out.println("Enter the length of the parallel sides of the trapezium: ");
        double side2=sc.nextDouble();
        System.out.println("Enter the height of the trapezium: ");
        double height = sc.nextDouble();
        //Calculate the area
        double area=((side1+side2)*height)/2;
       if (side1 <= 0 || side2<=0)
            System.out.println("Length should be positve");
        else
            System.out.println("Area of trapezium = "+ area);
     }
}

输入斜方肌平行边长度:6
输入斜方肌平行边长度:8
输入斜方肌高度:6
斜方肌面积= 42.0

Java 程序:程序 2:寻找梯形面积

在这个程序中,我们将学习当给定梯形的所有边时,如何找到梯形的面积。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明变量来存储梯形边的值。
  4. 要求用户初始化变量。
  5. 声明另一个变量来存储梯形的半周长。
  6. 从梯形的半周长减去边。
  7. 计算上述结果的平方根。
  8. 现在,用公式计算梯形的面积。
  9. 显示结果。
  10. 停下来。

下面的程序演示了如何找到梯形的面积。

//Java Program to Calculate the Area of a Trapezium
import java.util.Scanner;
public class Main
{
     public static void main(String []args)
     {
        //Take input from the user 
        //Create an instance of the Scanner Class
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the length of the longer side of the trapezium: ");
        double a=sc.nextDouble();
        System.out.println("Enter the length of the shorter side of the trapezium: ");
        double b=sc.nextDouble();
        System.out.println("Enter the length of the non-parallel side of the trapezium: ");
        double c = sc.nextDouble();
         System.out.println("Enter the length of the non-parallel side of the trapezium: ");
        double d = sc.nextDouble();
        double s =(a+b+c+d)/2;
        double num=(s-a)*(s-b)*(s-b-c)*(s-b-d);
        double res=Math.sqrt(num);
        //Calculate the area
        double Area =(a+b)/(a-b)*res;
       if (a <= 0 || b<=0 || c<=0 || d<=0)
            System.out.println("Length should be positve");
        else
            System.out.println("Area of trapezium = "+ Area);
     }
}

输入斜方肌长边长度:14
输入斜方肌短边长度:6
输入斜方肌非平行边长度:5
输入斜方肌非平行边长度:5
斜方肌面积= 30.0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值