首页 > 编程语言 >BeginnersBook-Java-示例-一-

BeginnersBook-Java-示例-一-

时间:2024-10-24 18:15:34浏览次数:1  
标签:Java String 示例 int System out public BeginnersBook

BeginnersBook Java 示例(一)

原文:BeginnersBook

协议:CC BY-NC-SA 4.0

Java 程序:计算复合利率

原文: https://beginnersbook.com/2019/07/java-program-to-calculate-compound-interest/

在本教程中,我们将编写一个 java 程序来计算复合利率

复利计算公式

使用以下公式计算复利:

P (1 + R/n) (nt) - P

这里P是本金额。
R是年利率。
t是投资或借入资金的时间。
n是每单位 t 复利的次数,例如,如果利息按月复利而t为年,则 n 的值为 12。如果利息按季度复利,t是以年为单位,则n的值为 4。

在编写 java 程序之前,我们以一个例子来计算复合利率。

假设 2000 美元的金额作为定期存款存入银行账户,年利率为 8%,每月复利,5 年后的复利将是:

P = 2000
R = 8/100 = 0.08(十进制)
n = 12
t = 5

我们将这些值放在公式中。

复利 = 2000 (1 + 0.08 / 12) (12 * 5) - 2000 = $ 979.69

因此,5 年后的复利为 979.69 美元。

用于计算复合利率的 Java 程序

在这个 java 程序中,我们正在计算复合利率,我们正在考虑上面我们在计算中看到的相同的例子

public class JavaExample {

    public void calculate(int p, int t, double r, int n) {
        double amount = p * Math.pow(1 + (r / n), n * t);
        double cinterest = amount - p;
        System.out.println("Compound Interest after " + t + " years: "+cinterest);
        System.out.println("Amount after " + t + " years: "+amount);
    }
    public static void main(String args[]) {
    	JavaExample obj = new JavaExample();
    	obj.calculate(2000, 5, .08, 12);
    }
}

输出:

Compound Interest after 5 years: 979.6914166032102
Amount after 5 years: 2979.69141660321

Eclipse IDE 的屏幕截图:

Java Program to calculate compound interest

相关的 Java 示例

  1. Java 程序:计算学生成绩
  2. Java 程序:使用数组计算平均值
  3. Java 程序:计算圆的面积和周长
  4. Java 程序:计算三角形面积

Java 程序:计算简单利率

原文: https://beginnersbook.com/2019/07/java-program-to-calculate-simple-interest/

在本教程中,我们将编写一个 java 程序来计算简单的利率

要编写复合感利率的程序,请参考本指南:程序来计算复合利率

简单利率公式

Simple Interest = (P × R × T)/100

P是本金。
R是每年的费率。
T是多年的时间。

例如:假设一个人在银行账户中存入 2000 INR,年利率为 6%,为期 3 年,计算 3 年末的简单利息。

Simple Interest = 2000 * 6 * 3/100 = 360 INR

Java 程序:计算简单的利率

在下面的例子中,我们从用户获取prt的值,然后我们根据输入的值计算简单利率。

import java.util.Scanner;
public class JavaExample
{
    public static void main(String args[]) 
    {
        float p, r, t, sinterest;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the Principal : ");
        p = scan.nextFloat();
        System.out.print("Enter the Rate of interest : ");
        r = scan.nextFloat();
        System.out.print("Enter the Time period : ");
        t = scan.nextFloat();
        scan.close();
        sinterest = (p * r * t) / 100;
        System.out.print("Simple Interest is: " +sinterest);
    }
}

输出:

Enter the Principal : 2000
Enter the Rate of interest : 6
Enter the Time period : 3
Simple Interest is: 360.0

Eclipse IDE 的屏幕截图:

Java Program to calculate simple interest

相关的 Java 示例

  1. Java 程序:使用数组计算值的平均值
  2. Java 程序:计算正方形面积
  3. Java 程序:打印备用素数
  4. Java 程序:打印 pascal 三角形

Java 程序:查找商和余数

原文: https://beginnersbook.com/2019/08/java-program-to-find-quotient-and-remainder/

在本文中,我们将编写一个 Java 程序来查找商数和余数,当一个数字除以另一个数字时。

示例:用于查找商和余数的程序

在下面的程序中,我们有两个整数num1num2,当num1除以num2时我们找到商和余数,所以我们可以说num1被除数,而num2除数

public class JavaExample {
    public static void main(String[] args) {
        int num1 = 15, num2 = 2;
        int quotient = num1 / num2;
        int remainder = num1 % num2;
        System.out.println("Quotient is: " + quotient);
        System.out.println("Remainder is: " + remainder);
    }
}

输出:

Java Program to Find Quotient and Remainder

计算商和余数,我们分别创建了两个名为quotientremainder的变量。

为了找到,我们使用/运算符将num1除以num2。由于变量num1num2是整数,尽管15/2的结果在数学上是 7.5,但结果将是整数。因此,操作后分配给变量quotient的值为 7。

要找到余数,我们使用%运算符。操作后,将15/2的余数(即 1)分配给变量remainder

在程序结束时,打印变量quotientremainder的值。

相关的 Java 示例

  1. Java 程序:计算简单兴趣
  2. Java 程序:进行选择排序
  3. Java 程序:打印备用素数
  4. Java 程序:计算字符串中出现的字符
  5. Java 程序:将整数分解为数字

Java 字符串程序

如何在 Java 中将字符串转换为char

原文: https://beginnersbook.com/2014/06/how-to-convert-char-to-string-and-a-string-to-char-in-java/

在本教程中,我们将看到charStringStringchar转换的程序。

char转换为String

我们有以下两种方式进行字符串转换。
方法 1:使用toString()方法
方法 2:使用valueOf()方法

class CharToStringDemo
{
   public static void main(String args[])
   {
      // Method 1: Using toString() method
      char ch = 'a';
      String str = Character.toString(ch);
      System.out.println("String is: "+str);

      // Method 2: Using valueOf() method
      String str2 = String.valueOf(ch);
      System.out.println("String is: "+str2);
   }
}

输出:

String is: a
String is: a

将字符串转换为字符

我们可以使用StringcharAt()方法String转换为char

class StringToCharDemo
{
   public static void main(String args[])
   {
      // Using charAt() method
      String str = "Hello";
      for(int i=0; i<str.length();i++){
        char ch = str.charAt(i);
        System.out.println("Character at "+i+" Position: "+ch);
      } 
   }
}

输出:

Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o

Java 程序:在String中查找重复的字符

原文: https://beginnersbook.com/2014/07/java-program-to-find-duplicate-characters-in-a-string/

该程序将找出String中的重复字符并显示它们的计数。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Details {

  public void countDupChars(String str){

    //Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 

    //Convert the String to char array
    char[] chars = str.toCharArray();

    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }

    //Obtaining set of keys
    Set<Character> keys = map.keySet();

    /* Display count of chars if it is
     * greater than 1\. All duplicate chars would be 
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }

  public static void main(String a[]){
    Details obj = new Details();
    System.out.println("String: BeginnersBook.com");
    System.out.println("-------------------------");
    obj.countDupChars("BeginnersBook.com");

    System.out.println("\nString: ChaitanyaSingh");
    System.out.println("-------------------------");
    obj.countDupChars("ChaitanyaSingh");

    System.out.println("\nString: #@[email protected]!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@[email protected]!#$%!!%@");
  }
}

输出:

String: BeginnersBook.com
-------------------------
Char e 2
Char B 2
Char n 2
Char o 3

String: ChaitanyaSingh
-------------------------
Char a 3
Char n 2
Char h 2
Char i 2

String: #@[email protected]!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2

参考:

HashMap

java 程序:使用StackQueueforwhile循环检查回文串

原文: https://beginnersbook.com/2014/01/java-program-to-check-palindrome-string/

在本教程中,我们将看到程序来检查给定的String是否是回文。以下是实现目标的方法。

1)使用堆栈

2)使用队列

3)使用for/while循环

程序 1:使用堆栈进行回文检查

import java.util.Stack;
import java.util.Scanner;
class PalindromeTest {

    public static void main(String[] args) {

    	System.out.print("Enter any string:");
        Scanner in=new Scanner(System.in);
        String inputString = in.nextLine();
        Stack stack = new Stack();

        for (int i = 0; i < inputString.length(); i++) {
            stack.push(inputString.charAt(i));
        }

        String reverseString = "";

        while (!stack.isEmpty()) {
            reverseString = reverseString+stack.pop();
        }

        if (inputString.equals(reverseString))
            System.out.println("The input String is a palindrome.");
        else
            System.out.println("The input String is not a palindrome.");

    }
}

输出 1:

Enter any string:abccba
The input String is a palindrome.

输出 2:

Enter any string:abcdef
The input String is not a palindrome.

程序 2:回顾检查使用队列

import java.util.Queue;
import java.util.Scanner;
import java.util.LinkedList;
class PalindromeTest {

    public static void main(String[] args) {

    	System.out.print("Enter any string:");
        Scanner in=new Scanner(System.in);
        String inputString = in.nextLine();
        Queue queue = new LinkedList();

        for (int i = inputString.length()-1; i >=0; i--) {
            queue.add(inputString.charAt(i));
        }

        String reverseString = "";

        while (!queue.isEmpty()) {
            reverseString = reverseString+queue.remove();
        }
        if (inputString.equals(reverseString))
            System.out.println("The input String is a palindrome.");
        else
            System.out.println("The input String is not a palindrome.");

    }
}

输出 1:

Enter any string:xyzzyx
xyzzyx
The input String is a palindrome.

输出 2:

Enter any string:xyz
The input String is not a palindrome.

程序 3:使用for循环/While循环和字符串函数charAt

import java.util.Scanner;
class PalindromeTest {
   public static void main(String args[])
   {
      String reverseString="";
      Scanner scanner = new Scanner(System.in);

      System.out.println("Enter a string to check if it is a palindrome:");
      String inputString = scanner.nextLine();

      int length = inputString.length();

      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverseString = reverseString + inputString.charAt(i);

      if (inputString.equals(reverseString))
         System.out.println("Input string is a palindrome.");
      else
         System.out.println("Input string is not a palindrome.");

   }
}

输出 1:

Enter a string to check if it is a palindrome:
aabbaa
Input string is a palindrome.

输出 2:

Enter a string to check if it is a palindrome:
aaabbb
Input string is not a palindrome.

如果你想在上面的程序中使用While循环,那么用这段代码替换for循环:

int i = length-1;
while ( i >= 0){
    reverseString = reverseString + inputString.charAt(i);
    i--;
}

Java 程序:按字母顺序排序字符串

原文: https://beginnersbook.com/2018/10/java-program-to-sort-strings-in-an-alphabetical-order/

在这个 java 教程中,我们将学习如何按字母顺序对字符串进行排序。

Java 示例:按字母顺序排列字符串

在这个程序中,我们要求用户输入他想要输入的字符串计数以进行排序。一旦使用Scanner类捕获计数,我们已初始化输入计数大小的String数组,然后运行for循环以捕获用户输入的所有字符串。

一旦我们将所有字符串存储在字符串数组中,我们就会比较每个字符串的第一个字母,以便按字母顺序对它们进行排序。

import java.util.Scanner;
public class JavaExample
{
    public static void main(String[] args) 
    {
        int count;
        String temp;
        Scanner scan = new Scanner(System.in);

        //User will be asked to enter the count of strings 
        System.out.print("Enter number of strings you would like to enter:");
        count = scan.nextInt();

        String str[] = new String[count];
        Scanner scan2 = new Scanner(System.in);

        //User is entering the strings and they are stored in an array
        System.out.println("Enter the Strings one by one:");
        for(int i = 0; i < count; i++)
        {
            str[i] = scan2.nextLine();
        }
        scan.close();
        scan2.close();

        //Sorting the strings
        for (int i = 0; i < count; i++) 
        {
            for (int j = i + 1; j < count; j++) { 
                if (str[i].compareTo(str[j])>0) 
                {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }

        //Displaying the strings after sorting them based on alphabetical order
        System.out.print("Strings in Sorted Order:");
        for (int i = 0; i <= count - 1; i++) 
        {
            System.out.print(str[i] + ", ");
        }
    }
}

输出:

Java Program to Sort Strings in an Alphabetical Order

相关 Java 示例:

  1. Java 程序:在字符串中反转单词
  2. Java 程序:计算和打印学生成绩
  3. Java 程序:使用递归反转字符串
  4. Java 程序:查找字符串中的重复字符

Java 程序:反转String中的单词

原文: https://beginnersbook.com/2017/09/java-program-to-reverse-words-in-a-string/

该程序反转字符串的每个单词并将反转的字符串显示为输出。例如,如果我们输入一个字符串"reverse the word of this string",那么程序的输出将是:"esrever eht drow fo siht gnirts"

要了解此程序,您应该具有以下 Java 编程主题的知识:

  1. Java for循环
  2. Java String split()方法
  3. Java String charAt()方法

示例:使用方法反转String中的每个单词

在本程序中,我们首先使用split()方法将给定的字符串拆分为子字符串。子串存储在String数组words中。程序然后使用反向的for循环反转子串的每个单词。

public class Example
{
   public void reverseWordInMyString(String str)
   {
	/* The split() method of String class splits
	 * a string in several strings based on the
	 * delimiter passed as an argument to it
	 */
	String[] words = str.split(" ");
	String reversedString = "";
	for (int i = 0; i < words.length; i++)
        {
           String word = words[i]; 
           String reverseWord = "";
           for (int j = word.length()-1; j >= 0; j--) 
	   {
		/* The charAt() function returns the character
		 * at the given position in a string
		 */
		reverseWord = reverseWord + word.charAt(j);
	   }
	   reversedString = reversedString + reverseWord + " ";
	}
	System.out.println(str);
	System.out.println(reversedString);
   }
   public static void main(String[] args) 
   {
	Example obj = new Example();
	obj.reverseWordInMyString("Welcome to BeginnersBook");
	obj.reverseWordInMyString("This is an easy Java Program");
   }
}

输出:

Welcome to BeginnersBook
emocleW ot kooBsrennigeB 
This is an easy Java Program
sihT si na ysae avaJ margorP

看看这些相关的 java 程序

  1. Java 程序:反转数字
  2. Java 程序:反转字符串
  3. Java 程序:反转数组
  4. Java 程序:使用循环检查 Palindrome 字符串

Java 程序:对字符串执行冒泡排序

原文: https://beginnersbook.com/2019/04/java-program-to-perform-b​​ubble-sort-on-strings/

要对字符串执行冒泡排序,我们需要比较相邻的字符串,如果它们不在顺序中,那么我们需要交换这些字符串,这个过程需要完成,直到我们到达最后。这样,所有字符串都将按升序排序,这种排序过程称为冒泡排序。

字符串上的冒泡排序示例

在下面的示例中,我们将字符串存储在String数组中,并且我们使用嵌套for循环来比较数组中的相邻字符串,如果它们不是按顺序我们使用临时字符串变量temp交换它们

这里我们使用compareTo()方法来比较相邻的字符串。

public class JavaExample {
   public static void main(String []args) {
	String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan"};
	String temp;
	System.out.println("Strings in sorted order:");
	for (int j = 0; j < str.length; j++) {
   	   for (int i = j + 1; i < str.length; i++) {
		// comparing adjacent strings
		if (str[i].compareTo(str[j]) < 0) {
			temp = str[j];
			str[j] = str[i];
			str[i] = temp;
		}
	   }
	   System.out.println(str[j]);
	}
   }
}

输出:

Java bubble sort on strings example

相关的 Java 示例

  1. Java 程序:排序数组
  2. Java 程序:按字母顺序排序字符串
  3. Java 程序:反转字符串中的单词
  4. Java 程序:查找字符串中的重复字符

Java 基础程序

Java 程序:查找字符串中字符的出现

原文: https://beginnersbook.com/2019/04/java-program-to-find-the-occurrence-of-a-character-in-a-string/

在本教程中,我们将编写一个 Java 程序来查找String中字符的出现。

编程以查找字符串中字符的出现

在这个程序中,我们发现String中每个字符的出现。为此,我们首先创建一个大小为 256(ASCII 上限)的数组,这里的想法是将出现次数存储在该字符的 ASCII 值中。例如,'A'的出现将存储在计数器[65]中,因为A的 ASCII 值是 65,类似地,其他字符的出现存储在它们的 ASCII 索引值中。

然后我们创建另一个数组array来保存给定String的字符,然后我们将它们与String中的字符进行比较,当找到匹配时,使用counter数组显示该特定字符的计数。

class JavaExample {  

   static void countEachChar(String str) 
   { 
	//ASCII values ranges upto 256
	int counter[] = new int[256]; 

	//String length
	int len = str.length(); 

	/* This array holds the occurrence of each char, For example
	 * ASCII value of A is 65 so if A is found twice then 
	 * counter[65] would have the value 2, here 65 is the ASCII value
	 * of A
	 */
	for (int i = 0; i < len; i++) 
		counter[str.charAt(i)]++; 

	// We are creating another array with the size of String
	char array[] = new char[str.length()]; 
        for (int i = 0; i < len; i++) { 
	   array[i] = str.charAt(i); 
	   int flag = 0; 
	   for (int j = 0; j <= i; j++) { 

		/* If a char is found in String then set the flag 
		 * so that we can print the occurrence
		 */
		if (str.charAt(i) == array[j])  
			flag++;                 
	   } 

	   if (flag == 1)  
	      System.out.println("Occurrence of char " + str.charAt(i)
		 + " in the String is:" + counter[str.charAt(i)]);             
	} 
   } 
   public static void main(String[] args) 
   {  
	String str = "beginnersbook"; 
	countEachChar(str); 
   } 
}

输出:

Java program to find the occurrence of a character in a string

相关的 Java 程序

  1. Java 程序:按字母顺序排序字符串
  2. Java 程序:检查元音和辅音
  3. Java 程序:查找字符串中的重复字符
  4. Java 程序:检查回文串

Java 程序:计算字符串中的元音和辅音

原文: https://beginnersbook.com/2019/04/java-program-to-count-vowels-and-consonants-in-a-string/

在本文中,我们将编写一个 Java 程序来计算String中的元音和辅音。

用于计算给定字符串中的元音和辅音的程序

这里我们有两个变量vcountccount来分别保持元音和辅音的数量。我们已经使用toLowerCase()方法将字符串的每个字符串转换为小写,以便于比较。

然后我们使用charAt()方法if..else..if语句将字符串的每个字符串与元音'a''e''i''o''u'进行比较,如果找到匹配,那么我们正在增加元音计数器vcount,否则我们正在增加辅音计数器ccount

public class JavaExample {

    public static void main(String[] args) {
        String str = "BeginnersBook";
        int vcount = 0, ccount = 0;

        //converting all the chars to lowercase
        str = str.toLowerCase();
        for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vcount++; } else if((ch >= 'a'&& ch <= 'z')) {
                ccount++;
            }
        }
        System.out.println("Number of Vowels: " + vcount);
        System.out.println("Number of Consonants: " + ccount);
    }
}

输出:

Java program to count vowels and consonants in a String

相关的 Java 程序

  1. Java 程序:在字符串中查找字符的出现
  2. Java 程序:对字符串执行冒泡排序
  3. Java 程序:反转一个字符串
  4. Java 程序:使用Switch Case检查元音或辅音

Java 数组程序

Java 程序:使用数组计算平均值

原文: https://beginnersbook.com/2017/09/java-program-to-calculate-average-using-array/

我们将看到两个使用数组查找数字平均值的程序。第一个程序查找指定数组元素的平均值。第二个程序获取n(元素数)的值和用户提供的数字,并使用数组查找它们的平均值。

要了解这些程序,您应该具备以下 Java 编程概念的知识:

1) Java 数组

2) For循环

示例 1:使用数组查找数字平均值

public class JavaExample {

    public static void main(String[] args) {
        double[] arr = {19, 12.89, 16.5, 200, 13.7};
        double total = 0;

        for(int i=0; i<arr.length; i++){
        	total = total + arr[i];
        }

        /* arr.length returns the number of elements 
         * present in the array
         */
        double average = total / arr.length;

        /* This is used for displaying the formatted output
         * if you give %.4f then the output would have 4 digits
         * after decimal point.
         */
        System.out.format("The average is: %.3f", average);
    }
}

输出:

The average is: 52.418

示例 2:计算用户输入的数字的平均值

在此示例中,我们使用Scanner来获取n的值以及来自用户的所有数字。

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        System.out.println("How many numbers you want to enter?");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        /* Declaring array of n elements, the value
         * of n is provided by the user
         */
        double[] arr = new double[n];
        double total = 0;

        for(int i=0; i<arr.length; i++){
        	System.out.print("Enter Element No."+(i+1)+": ");
        	arr[i] = scanner.nextDouble();
        }
        scanner.close();
        for(int i=0; i<arr.length; i++){
        	total = total + arr[i];
        }

        double average = total / arr.length;

        System.out.format("The average is: %.3f", average);
    }
}

输出:

How many numbers you want to enter?
5
Enter Element No.1: 12.7
Enter Element No.2: 18.9
Enter Element No.3: 20
Enter Element No.4: 13.923
Enter Element No.5: 15.6
The average is: 16.225

Java 程序:汇总数组的元素

原文: https://beginnersbook.com/2014/01/java-program-to-sum-the-elements-of-an-array/

在本教程中,我们将看到如何汇总数组的所有元素。

计划 1:没有用户互动

/**
 * @author: BeginnersBook.com
 * @description: Get sum of array elements
 */
class SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      //Advanced for loop
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

输出:

Sum of array elements is:160

程序 2:用户输入数组的元素

/**
 * @author: BeginnersBook.com
 * @description: User would enter the 10 elements
 * and the program will store them into an array and 
 * will display the sum of them.
 */
import java.util.Scanner;
class SumDemo{
   public static void main(String args[]){
      Scanner scanner = new Scanner(System.in);
      int[] array = new int[10];
      int sum = 0;
      System.out.println("Enter the elements:");
      for (int i=0; i<10; i++)
      {
    	  array[i] = scanner.nextInt();
      }
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

输出:

Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

Java 程序:反转数组

原文: https://beginnersbook.com/2017/09/java-program-to-reverse-the-array/

该程序反转数组。例如,如果用户输入数组元素为1,2,3,4,5,那么程序将反转数组,数组元素将为5,4,3,2,1。要理解这个程序,你应该有以下 Java 编程主题的知识:

  1. Java 中的数组
  2. Java For循环
  3. Java While循环

示例:反转数组

import java.util.Scanner;
public class Example
{
   public static void main(String args[])
   {
	int counter, i=0, j=0, temp;
	int number[] = new int[100];
	Scanner scanner = new Scanner(System.in);
	System.out.print("How many elements you want to enter: ");
	counter = scanner.nextInt();

	/* This loop stores all the elements that we enter in an 
	 * the array number. First element is at number[0], second at 
	 * number[1] and so on
	 */
	for(i=0; i<counter; i++)
	{
	    System.out.print("Enter Array Element"+(i+1)+": ");
	    number[i] = scanner.nextInt();
	}

	/* Here we are writing the logic to swap first element with
	 * last element, second last element with second element and
	 * so on. On the first iteration of while loop i is the index 
	 * of first element and j is the index of last. On the second
	 * iteration i is the index of second and j is the index of 
	 * second last.
	 */
	j = i - 1;     
	i = 0;         
	scanner.close();
	while(i<j)
	{
  	   temp = number[i];
	   number[i] = number[j];
	   number[j] = temp;
	   i++;
	   j--;
	}

	System.out.print("Reversed array: ");
	for(i=0; i<counter; i++)
	{
	   System.out.print(number[i]+ "  ");
	}       
   }
}

输出:

How many elements you want to enter: 5
Enter Array Element1: 11
Enter Array Element2: 22
Enter Array Element3: 33
Enter Array Element4: 44
Enter Array Element5: 55
Reversed array: 55  44  33  22  11

看看这些相关的 java 程序

  1. Java 程序:反转字符串
  2. Java 程序:反转字符串
  3. Java 程序:反转数字

Java 程序:按升序排序数组

原文: https://beginnersbook.com/2018/10/java-program-to-sort-an-array-in-ascending-order/

在这个 java 教程中,我们使用临时变量和嵌套for循环按升序对数组进行排序。我们使用Scanner类来获取用户的输入。

Java 示例:按升序排序数组

在该程序中,要求用户输入他想要输入的元素的数量。根据输入,我们声明了一个int数组,然后我们接受用户输入的所有数字并将它们存储在数组中

一旦我们将所有数字存储在数组中,我们就会使用嵌套for循环对它们进行排序。

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
    	int count, temp;

    	//User inputs the array size
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter number of elements you want in the array: ");
        count = scan.nextInt();

        int num[] = new int[count];
        System.out.println("Enter array elements:");
        for (int i = 0; i < count; i++) 
        {
            num[i] = scan.nextInt();
        }
        scan.close();
        for (int i = 0; i < count; i++) 
        {
            for (int j = i + 1; j < count; j++) { 
                if (num[i] > num[j]) 
                {
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
        System.out.print("Array Elements in Ascending Order: ");
        for (int i = 0; i < count - 1; i++) 
        {
            System.out.print(num[i] + ", ");
        }
        System.out.print(num[count - 1]);
    }
}

输出:

Java Program to Sort an Array in Ascending Order

相关 Java 示例:

  1. Java 程序:按升序和降序排序
  2. Java 程序:使用按位 xor 运算符交换两个数字
  3. Java 程序:按字母顺序排序字符串
  4. Java 程序:反转数组

如何在 Java 中将char数组转换为字符串?

原文: https://beginnersbook.com/2014/06/how-to-convert-a-char-array-to-a-string-in-java/

在 Java 中有两种方法将char数组(char [])转换为String

1)通过将数组名称传递给构造函数
来创建String对象

2)使用StringvalueOf()方法

示例:

此示例演示了上述将char数组转换为String的方法。这里我们有一个char数组ch,我们使用char数组创建了两个字符串strstr1

class CharArrayToString
{
   public static void main(String args[])
   {
      // Method 1: Using String object
      char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
      String str = new String(ch);
      System.out.println(str);

      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);
      System.out.println(str2);
   }
}

输出:

good morning
good morning

Java 递归程序

Java 程序:使用forwhile和递归来反转一个数字

原文: https://beginnersbook.com/2014/01/java-program-to-reverse-a-number/

在 Java 中有三种方法可以反转数字。

1)使用while循环

2)使用for循环

3)使用递归

4)用户互动的反转数字

程序 1:使用while循环反转一个数字

程序将提示用户输入数字,然后使用while循环反转相同的数字。

import java.util.Scanner;
class ReverseNumberWhile
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
   }
}

输出:

Input your number and press enter: 
145689
Reverse of input number is: 986541

程序 2:使用for循环反转一个数字

import java.util.Scanner;
class ForLoopReverseDemo
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      /* for loop: No initialization part as num is already
       * initialized and no increment/decrement part as logic
       * num = num/10 already decrements the value of num
       */
      for( ;num != 0; )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of specified number is: "+reversenum);
   }
}

输出:

Input your number and press enter: 
56789111
Reverse of specified number is: 11198765

程序 3:使用递归反转数字

import java.util.Scanner;
class RecursionReverseDemo
{
   //A method for reverse
   public static void reverseMethod(int number) {
       if (number < 10) {
	   System.out.println(number);
	   return;
       }
       else {
           System.out.print(number % 10);
           //Method is calling itself: recursion
           reverseMethod(number/10);
       }
   }
   public static void main(String args[])
   {
	int num=0;
	System.out.println("Input your number and press enter: ");
	Scanner in = new Scanner(System.in);
	num = in.nextInt();
	System.out.print("Reverse of the input number is:");
	reverseMethod(num);
	System.out.println();
   }
}

输出:

Input your number and press enter: 
5678901
Reverse of the input number is:1098765

示例:反转已经初始化的数字

在上述所有程序中,我们正在提示用户输入数字,但是如果不想要用户交互部分并且想要反转初始化数字那么这就是你能行的。

class ReverseNumberDemo
{
   public static void main(String args[])
   {
      int num=123456789;
      int reversenum =0;
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of specified number is: "+reversenum);
   }
}

输出:

Reverse of specified number is: 987654321

Java 程序:相加两个数字

原文: https://beginnersbook.com/2017/09/java-program-to-add-two-numbers/

在这里我们将看到两个程序相加两个数字。在第一个程序中,我们指定程序本身中两个数字的值。第二个程序获取两个数字(由用户输入)并打印总和。

第一个例子:两个数字的总和

public class AddTwoNumbers {

   public static void main(String[] args) {

      int num1 = 5, num2 = 15, sum;
      sum = num1 + num2;

      System.out.println("Sum of these numbers: "+sum);
   }
}

输出:

Sum of these numbers: 20

第二个示例:使用Scanner的两个数字的总和

扫描仪允许我们捕获用户输入,以便我们可以从用户获取这两个数字的值。然后程序计算总和并显示它。

import java.util.Scanner;
public class AddTwoNumbers2 {

    public static void main(String[] args) {

        int num1, num2, sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        num1 = sc.nextInt();

        System.out.println("Enter Second Number: ");
        num2 = sc.nextInt();

        sc.close();
        sum = num1 + num2;
        System.out.println("Sum of these numbers: "+sum);
    }
}

输出:
Enter First Number: 
121
Enter Second Number: 
19
Sum of these numbers: 140

java 程序:使用递归检查回文字符串

原文: https://beginnersbook.com/2014/01/java-program-to-check-palindrome-string-using-recursion/

程序:使用递归检查String是否为回文

package beginnersbook.com;
import java.util.Scanner;
class PalindromeCheck
{
    //My Method to check
    public static boolean isPal(String s)
    {   // if length is 0 or 1 then String is palindrome
        if(s.length() == 0 || s.length() == 1)
            return true; 
        if(s.charAt(0) == s.charAt(s.length()-1))
        /* check for first and last char of String:
         * if they are same then do the same thing for a substring
         * with first and last char removed. and carry on this
         * until you string completes or condition fails
         * Function calling itself: Recursion
         */
        return isPal(s.substring(1, s.length()-1));

        /* If program control reaches to this statement it means
         * the String is not palindrome hence return false.
         */
        return false;
    }

    public static void main(String[]args)
    {
    	//For capturing user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the String for check:");
        String string = scanner.nextLine();
        /* If function returns true then the string is
         * palindrome else not
         */
        if(isPal(string))
            System.out.println(string + " is a palindrome");
        else
            System.out.println(string + " is not a palindrome");
    }
}

输出:

Enter the String for check:
qqaabb
qqaabb is not a palindrome

输出 2:

Enter the String for check:
cocoococ
cocoococ is a palindrome

Java 程序:使用递归来反转字符串

原文: https://beginnersbook.com/2017/09/java-program-to-reverse-a-string-using-recursion/

我们将看到两个程序来反转一个字符串。第一个程序使用递归反转给定的字符串,第二个程序读取用户输入的字符串然后反转它。

要了解这些程序,你应该具备以下核心 java 概念的知识:

1)substring()

2)charAt()方法

示例 1:用于反转字符串的程序

public class JavaExample {

    public static void main(String[] args) {
        String str = "Welcome to Beginnersbook";
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

输出:

The reversed string is: koobsrennigeB ot emocleW

示例 2:用于反转用户输入的字符串的程序

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        String str;
        System.out.println("Enter your username: ");
        Scanner scanner = new Scanner(System.in);
        str = scanner.nextLine();
        scanner.close();
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

输出:

Enter your username: 
How are you doing?
The reversed string is: ?gniod uoy era woH

java 程序:使用递归查找给定数字的阶乘

原文: https://beginnersbook.com/2014/01/java-program-to-find-factorial-of-a-given-number-using-recursion/

在这里,我们将编写程序,使用递归找出数字的阶乘。

程序 1:

程序将提示用户输入数字。一旦用户提供输入,程序将计算所提供输入数的阶乘。

/**
 * @author: BeginnersBook.com
 * @description: User would enter the 10 elements
 * and the program will store them into an array and 
 * will display the sum of them.
 */
import java.util.Scanner;
class FactorialDemo{
   public static void main(String args[]){
      //Scanner object for capturing the user input
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the number:");
      //Stored the entered value in variable
      int num = scanner.nextInt();
      //Called the user defined function fact
      int factorial = fact(num);
      System.out.println("Factorial of entered number is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}

输出:

Enter the number:
5
Factorial of entered number is: 120

程序 2:

如果您不想要用户干预并且只想在程序中指定数字,请参考此示例。

class FactorialDemo2{
   public static void main(String args[]){
      int factorial = fact(4);
      System.out.println("Factorial of 4 is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}

输出:

Factorial of 4 is: 24

Java 数字程序

Java 程序:显示前n个或前 100 个素数

原文: https://beginnersbook.com/2014/01/java-program-to-display-first-n-or-first-100-prime-numbers/

显示前n个素数的程序

import java.util.Scanner;

class PrimeNumberDemo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      //For capturing the value of n
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the value of n:");
      //The entered value is stored in the var n
      n = scanner.nextInt();
      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are:");
         //2 is a known prime number
         System.out.println(2);
      }

      for ( int i = 2 ; i <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }         
   }
}

输出:

Enter the value of n:
15
First 15 prime numbers are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

显示前 100 个素数的程序

要显示前 100 个素数,你可以在上述程序中输入n值为 100 或者写一个这样的程序:

class PrimeNumberDemo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      System.out.println("First 100 prime numbers are:");   
      System.out.println(2);
      for ( int i = 2 ; i <=100 ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }         
   }
}

输出:

First 100 prime numbers are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541

Java 程序:显示 1 到 100 和 1 到n的素数

原文: https://beginnersbook.com/2014/01/java-program-to-display-prime-numbers/

只能被 1 和自身整除的数字称为素数。例如,2,3,5,7 ......是素数。在这里我们将看到两个程序:

1)第一个程序将打印 1 到 100 之间的素数

2)第二个程序取n的值(由用户输入)并打印 1 到n之间的素数。

如果您正在寻找一个程序来检查输入的数字是否为素数,请参阅: Java 程序:检查素数

显示从 1 到 100 的素数

它将显示 1 到 100 之间的素数。

class PrimeNumbers
{
   public static void main (String[] args)
   {		
       int i =0;
       int num =0;
       //Empty String
       String  primeNumbers = "";

       for (i = 1; i <= 100; i++)         
       { 		  	  
          int counter=0; 	  
          for(num =i; num>=1; num--)
	  {
             if(i%num==0)
	     {
 		counter = counter + 1;
	     }
	  }
	  if (counter ==2)
	  {
	     //Appended the Prime number to the String
	     primeNumbers = primeNumbers + i + " ";
	  }	
       }	
       System.out.println("Prime numbers from 1 to 100 are :");
       System.out.println(primeNumbers);
   }
}

输出:

Prime numbers from 1 to 100 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

显示从 1 到n的素数

它将显示 1 和n之间的所有素数(n是用户输入的数字)。

import java.util.Scanner;
class PrimeNumbers2
{
   public static void main (String[] args)
   {		
      Scanner scanner = new Scanner(System.in);
      int i =0;
      int num =0;
      //Empty String
      String  primeNumbers = "";
      System.out.println("Enter the value of n:");
      int n = scanner.nextInt();
      scanner.close();
      for (i = 1; i <= n; i++)  	   
      { 		 		  
         int counter=0; 		  
         for(num =i; num>=1; num--)
         {
	    if(i%num==0)
	    {
		counter = counter + 1;
	    }
	 }
	 if (counter ==2)
	 {
	    //Appended the Prime number to the String
	    primeNumbers = primeNumbers + i + " ";
	 }	
      }	
      System.out.println("Prime numbers from 1 to n are :");
      System.out.println(primeNumbers);
   }
}

输出:

Enter the value of n:
150
Prime numbers from 1 to n are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 
97 101 103 107 109 113 127 131 137 139 149

Java 程序:将Integer分解为数字

原文: https://beginnersbook.com/2019/02/java-program-to-break-integer-into-digits/

在本教程中,我们将编写一个 java 程序来将输入整数分成数字。例如,如果输入的数字是 912,则程序应显示数字2,1,9以及它们在输出中的位置。

Java 示例:将整数分成数字

这里我们使用Scanner类来从用户获取输入。在第一个while循环中,我们计算输入数字中的数字,然后在第二个while循环中,我们使用模数运算符从输入数字中提取数字。

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num, temp, digit, count = 0;

        //getting the number from user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number:");
        num = scanner.nextInt();
        scanner.close();

        //making a copy of the input number
        temp = num;

        //counting digits in the input number
        while(num > 0)
        {
            num = num / 10;
            count++;
        }
        while(temp > 0)
        {
            digit = temp % 10;
            System.out.println("Digit at place "+count+" is: "+digit);
            temp = temp / 10;
            count--;
        }
    }
}

输出:

Java Program to break Integer into Digits

Java 程序:检查素数

原文: https://beginnersbook.com/2014/01/java-program-to-check-prime-number/

只能被 1 和自身整除的数字称为素数,例如 7 是素数,因为它只能被 1 和自身整除
这个程序取数字(由用户)然后检查输入数字是否为素数。然后程序显示结果。如果您正在寻找一个显示两个时间间隔之间的素数的程序,请参阅: Java 程序,用于显示 1 到n之间的素数

示例:用于检查输入数字是否为素数的程序

要理解这个程序,你应该知道for循环if-else语句break语句

import java.util.Scanner;
class PrimeCheck
{
   public static void main(String args[])
   {		
	int temp;
	boolean isPrime=true;
	Scanner scan= new Scanner(System.in);
	System.out.println("Enter any number:");
	//capture the input in an integer
	int num=scan.nextInt();
        scan.close();
	for(int i=2;i<=num/2;i++)
	{
           temp=num%i;
	   if(temp==0)
	   {
	      isPrime=false;
	      break;
	   }
	}
	//If isPrime is true then the number is prime else not
	if(isPrime)
	   System.out.println(num + " is a Prime Number");
	else
	   System.out.println(num + " is not a Prime Number");
   }
}

输出:

Enter any number:
19
19 is a Prime Number

输出 2:

Enter any number:
6
6 is not a Prime Number

您也可以使用while循环来检查素数:
只需替换上面程序中的这部分代码:

for(int i=2;i<=num/2;i++)
{
   temp=num%i;
   if(temp==0)
   {
      isPrime=false;
      break;
   }
}

有了这个:

int i=2;
while(i<= num/2)
{
   if(num % i == 0)
   {
	isPrime = false;
	break;
   }
   i++;
}

Java 程序:检查给定数字是否为完美平方

原文: https://beginnersbook.com/2019/02/java-program-to-check-if-given-number-is-perfect-square/

在本教程中,我们将编写一个 java 程序到,检查给定的数字是否为完美平方

Java 示例:检查数字是否是完美平方

在这个程序中,我们创建了一个用户定义的方法 checkPerfectSquare(),它接受一个数字作为参数,如果数字是完美的正方形则返回true,否则返回false

在用户定义的方法中,我们使用Math类的两种方法,sqrt()方法和floor()方法。Math.sqrt()方法找到给定数字的平方根,floor()方法找到sqrt()方法返回的平方根值的最接近整数。后来我们计算了这两者之间的差异,以检查差异是零还是非零。对于完美的平方数,这个差值应该为零,因为完美平方数的平方根本身就是整数。

package com.beginnersbook;
import java.util.Scanner;
class JavaExample { 

    static boolean checkPerfectSquare(double x)  
    { 

	// finding the square root of given number 
	double sq = Math.sqrt(x); 

	/* Math.floor() returns closest integer value, for
	 * example Math.floor of 984.1 is 984, so if the value
	 * of sq is non integer than the below expression would
	 * be non-zero.
	 */
	return ((sq - Math.floor(sq)) == 0); 
    } 

    public static void main(String[] args)  
    { 
	System.out.print("Enter any number:");
	Scanner scanner = new Scanner(System.in);
	double num = scanner.nextDouble(); 
	scanner.close();

	if (checkPerfectSquare(num)) 
		System.out.print(num+ " is a perfect square number"); 
	else
		System.out.print(num+ " is not a perfect square number"); 
    } 
}

输出:

Java Program to check perfect square

相关的 Java 示例

  1. Java 程序:将整数分解为数字
  2. Java 程序:检查阿姆斯特朗数
  3. Java 程序:检查素数
  4. Java 程序:检查闰年

Java 程序:不使用sqrt查找数字的平方根

原文: https://beginnersbook.com/2019/02/java-program-to-find-square-root-of-a-number-without-sqrt/

找到数字的平方根非常容易,我们可以使用Math.sqrt()方法找出任​​意数字的平方根。但是在本教程中我们将做一些不同的事情,我们将编写一个 java 程序来找到没有sqrt()方法的数字的平方根

Java 示例:不使用sqrt()方法查找平方根

在下面的程序中,我们创建了一个方法squareRoot(),在方法中我们编写了一个方程式,用于查找数字的平方根。对于方程式,我们使用while循环

package com.beginnersbook;
import java.util.Scanner;
class JavaExample { 

    public static double squareRoot(int number) {
	double temp;

	double sr = number / 2;

	do {
		temp = sr;
		sr = (temp + (number / temp)) / 2;
	} while ((temp - sr) != 0);

	return sr;
    }

    public static void main(String[] args)  
    { 
	System.out.print("Enter any number:");
	Scanner scanner = new Scanner(System.in);
	int num = scanner.nextInt(); 
	scanner.close();

	System.out.println("Square root of "+ num+ " is: "+squareRoot(num));
    } 
}

输出:

Java Program to find out the square root of a given number

相关的 Java 示例

  1. Java 程序:检查完美平方数
  2. Java 程序:打破数字
  3. Java 程序:查找两个数字的 GCD
  4. Java 程序:显示斐波那契序列

Java 程序:检查偶数或奇数

原文: https://beginnersbook.com/2014/02/java-program-to-check-even-or-odd-number/

import java.util.Scanner;

class CheckEvenOdd
{
  public static void main(String args[])
  {
    int num;
    System.out.println("Enter an Integer number:");

    //The input provided by user is stored in num
    Scanner input = new Scanner(System.in);
    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("Entered number is even");
     else
        System.out.println("Entered number is odd");
  }
}

输出 1:

Enter an Integer number:
78
Entered number is even

输出 2:

Enter an Integer number:
77
Entered number is odd

Java 程序:在给定范围之间打印 Armstrong 数字

原文: https://beginnersbook.com/2019/02/java-program-to-print-armstrong-numbers-between-a-given-range/

我们已经看过 java 程序来检查 Armstrong 数字。在本教程中,我们将编写一个 java 程序来打印给定范围之间的 Armstrong 数字。

Java 示例:在给定范围之间打印 Armstrong 数字

在此程序中,要求用户输入起始和结束数字,程序然后在这些输入数字之间打印 Armstrong 数字。

package com.beginnersbook;
import java.util.Scanner;

public class JavaExample
{
    public static void main(String args[])
    {
	int num, start, end, i, rem, temp, counter=0;

	Scanner scanner = new Scanner(System.in);
	System.out.print("Enter the start number: ");
	start = scanner.nextInt();
	System.out.print("Enter the end number: ");
	end = scanner.nextInt();
	scanner.close();

	//generate Armstrong numbers between start and end
	for(i=start+1; i<end; i++)
	{
	   temp = i;
	   num = 0;
	   while(temp != 0)
	   {
		rem = temp%10;
		num = num + rem*rem*rem;
		temp = temp/10;
	   }
	   if(i == num)
	   {
		if(counter == 0)
		{
		   System.out.print("Armstrong Numbers Between "+start+" and "+end+": ");
		}
		   System.out.print(i + "  ");
		   counter++;
	   }
	}
	// if no Armstrong number is found
	if(counter == 0)
	{
	   System.out.print("There is no Armstrong number Between "+start+" and "+end);
	}
    }
}

输出:

Java program to Print Armstrong numbers between a given range

相关的 Java 示例

  1. Java 程序:打印 Pascal 三角形
  2. Java 程序:将整数分解为数字
  3. Java 程序:打印给定范围之间的素数
  4. Java 程序:生成随机数

Java 程序:查找自然数之和

原文: https://beginnersbook.com/2017/09/java-program-to-find-sum-of-natural-numbers/

正整数1,2,3,4等被称为自然数。在这里,我们将看到三个程序来计算和显示自然数的总和。

  • 第一个程序使用while循环计算总和
  • 第二个程序使用for循环计算总和
  • 第三个程序取n的值(由用户输入)并计算n个自然数的总和

要了解这些程序,您应该熟悉核心 Java 教程的以下概念:

示例 1:使用while循环查找自然数之和的程序

public class Demo {

    public static void main(String[] args) {

       int num = 10, count = 1, total = 0;

       while(count <= num)
       {
           total = total + count;
           count++;
       }

       System.out.println("Sum of first 10 natural numbers is: "+total);
    }
}

输出:

Sum of first 10 natural numbers is: 55

示例 2:使用for循环计算自然数之和的程序

public class Demo {

    public static void main(String[] args) {

       int num = 10, count, total = 0;

       for(count = 1; count <= num; count++){
           total = total + count;
       }

       System.out.println("Sum of first 10 natural numbers is: "+total);
    }
}

输出:

Sum of first 10 natural numbers is: 55

示例 3:用于查找前n个(由用户输入)自然数之和的程序

import java.util.Scanner;
public class Demo {

    public static void main(String[] args) {

        int num, count, total = 0;

        System.out.println("Enter the value of n:");
        //Scanner is used for reading user input
        Scanner scan = new Scanner(System.in);
        //nextInt() method reads integer entered by user
        num = scan.nextInt();
        //closing scanner after use
        scan.close();
        for(count = 1; count <= num; count++){
            total = total + count;
        }

        System.out.println("Sum of first "+num+" natural numbers is: "+total);
    }
}

输出:

Enter the value of n:
20
Sum of first 20 natural numbers is: 210

Java 程序:用于检查数字是正还是负

原文: https://beginnersbook.com/2017/09/java-program-to-check-if-number-is-positive-or-negative/

在这篇文章中,我们将编写两个 java 程序,第一个 java 程序检查指定的数字是正数还是负数。第二个程序获取输入数字(由用户输入)并检查它是正数还是负数并显示结果。
→如果一个数字大于零,那么它是一个正数
→如果一个数字小于零那么它是一个负数
→如果一个数字等于零则它既不是负数也不是整数。

让我们在 Java 程序中编写这个逻辑。

示例 1:检查给定数字是正数还是负数

在此程序中,我们在声明期间指定了数字的值,程序检查指定的数字是正数还是负数。要理解这个程序,你应该具备核心 Java 编程if-else-if语句的基本知识。

public class Demo
{
    public static void main(String[] args) 
    {
        int number=109;
        if(number > 0)
        {
            System.out.println(number+" is a positive number");
        }
        else if(number < 0)
        {
            System.out.println(number+" is a negative number");
        }
        else
        {
            System.out.println(number+" is neither positive nor negative");
        }
    }
}

输出:

109 is a positive number

示例 2:检查输入数字(由用户输入)是正数还是负数

这里我们使用Scanner读取用户输入的数字,然后程序检查并显示结果。

import java.util.Scanner;
public class Demo
{
    public static void main(String[] args) 
    {
        int number;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number you want to check:");
        number = scan.nextInt();
        scan.close();
        if(number > 0)
        {
            System.out.println(number+" is positive number");
        }
        else if(number < 0)
        {
            System.out.println(number+" is negative number");
        }
        else
        {
            System.out.println(number+" is neither positive nor negative");
        }
    }
}

输出:

Enter the number you want to check:-12
-12 is negative number

试试这些相关的程序

  1. Java 程序:相加两个数字
  2. Java 程序:乘以两个数字
  3. Java 程序:从标准输入读取数字

Java 程序:生成随机数

原文: https://beginnersbook.com/2014/04/java-program-to-generate-random-number-example/

示例:生成随机数的程序

在下面的程序中,我们使用Random类的nextInt()方法来实现我们的目的。

/* Program: Random number generator
 * Written by: Chaitanya from beginnersbook.com
 * Input: None
 * 输出:Random number between o and 200*/
import java.util.*;
class GenerateRandomNumber {
   public static void main(String[] args) {
      int counter;
      Random rnum = new Random();
      /* Below code would generate 5 random numbers
       * between 0 and 200.
       */
      System.out.println("Random Numbers:");
      System.out.println("***************");
      for (counter = 1; counter <= 5; counter++) {
         System.out.println(rnum.nextInt(200));
      }
   }
}

输出:

Random Numbers:
***************

135
173
5
17
15

上述程序的输出每次都不一样。无论何时运行此代码,它都会生成 0 到 200 之间的任意 5 个随机数。对于例如当我第二次运行它时,它给了我以下输出,这与上面的完全不同。

输出 2:

Random Numbers:
***************

46
99
191
7
134

Java 程序:检查 Armstrong 数

原文: https://beginnersbook.com/2017/09/java-program-to-check-armstrong-number/

在这里,我们将编写一个 java 程序,检查给定的数字是否为 Armstrong 数。我们将看到同一程序的两个变体。在第一个程序中,我们将在程序本身中分配数字,在第二个程序中,用户将输入数字,程序将检查输入数字是否为 Armstrong。

在我们完成该计划之前,让我们看看什么是阿姆斯特朗数字。如果以下等式适用于该数字,则一个数字称为 Armstrong 数:

xy..z = xn + yn+.....+ zn

其中n表示数字中的位数

例如,这是一个 3 位数的阿姆斯特朗数字

370 = 33 + 73 + o3
         = 27 + 343 + 0
         = 370

让我们在一个程序中写这个:
要理解本程序,您应该具备以下 Java 编程主题的知识:

  1. Java while循环
  2. Java if-else-if

示例 1:用于检查给定数字是否为 Armstrong 数的程序

public class JavaExample {

    public static void main(String[] args) {

        int num = 370, number, temp, total = 0;

        number = num;
        while (number != 0)
        {
            temp = number % 10;
            total = total + temp*temp*temp;
            number /= 10;
        }

        if(total == num)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

输出:

370 is an Armstrong number

在上面的程序中我们使用了while循环,但是你也可以使用for循环。要使用for循环,请使用以下代码替换程序的while循环部分:

for( ;number!=0;number /= 10){
    temp = number % 10;
    total = total + temp*temp*temp;
}

示例 2:用于检查输入数字是否为 Armstrong 的程序

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int num, number, temp, total = 0;
        System.out.println("Ënter 3 Digit Number");
        Scanner scanner = new Scanner(System.in);
        num = scanner.nextInt();
        scanner.close();
        number = num;

        for( ;number!=0;number /= 10)
        {
            temp = number % 10;
            total = total + temp*temp*temp;
        }

        if(total == num)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

输出:

Ënter 3 Digit Number
371
371 is an Armstrong number

查看相关程序:

  1. Java 程序:检查素数
  2. Java 程序:检查闰年
  3. Java 程序:检查偶数或奇数

Java 程序:查找两个数字的 GCD

原文: https://beginnersbook.com/2018/09/java-program-to-find-gcd-of-two-numbers/

两个数字的 GCD(最大公约数)是最大的正整数,它将两个数字整除而不留任何余数。例如。 30 和 45 的 GCD 是 15。GCD 也称为 HCF(最高公因子)。在教程中,我们将编写几个不同的 Java 程序来找出两个数字的 GCD。

如何在纸上找出 GCD?

为了找出两个数字的 GCD,我们将公因子乘以如下图所示:

Finding GCD of numbers in Java

示例 1:使用for循环查找两个数字的 GCD

在这个例子中,我们使用for循环找到两个给定数字的 GCD。

我们正在运行一个 for 循环,从 1 到较小的数字和内部循环,我们将这两个数字除以循环计数器i,范围从 1 到较小的数字值。如果i的值除以两个数字而没有余数,那么我们将该值赋给变量gcd。在循环结束时,变量gcd将具有最大数字,该数字除以两个数字而没有余数。

public class GCDExample1 {

    public static void main(String[] args) {

    	//Lets take two numbers 55 and 121 and find their GCD
        int num1 = 55, num2 = 121, gcd = 1;

        /* loop is running from 1 to the smallest of both numbers
         * In this example the loop will run from 1 to 55 because 55
         * is the smaller number. All the numbers from 1 to 55 will be 
         * checked. A number that perfectly divides both numbers would
         * be stored in variable "gcd". By doing this, at the end, the 
         * variable gcd will have the largest number that divides both
         * numbers without remainder.
         */
        for(int i = 1; i <= num1 && i <= num2; i++)
        {
            if(num1%i==0 && num2%i==0)
                gcd = i;
        }

        System.out.printf("GCD of %d and %d is: %d", num1, num2, gcd);
    }

}

输出:

GCD of 55 and 121 is: 11

示例 2:使用while循环查找两个数字的 GCD

让我们使用while循环编写相同的程序。在这里,我们采用不同的方法来寻找 gcd。在这个程序中,我们从较大的数字中减去较小的数字,直到它们变得相同。在循环结束时,数字的值将相同,并且该值将是这些数字的 GCD。

public class GCDExample2 {

    public static void main(String[] args) {

        int num1 = 55, num2 = 121;

        while (num1 != num2) {
        	if(num1 > num2)
                num1 = num1 - num2;
            else
                num2 = num2 - num1;
        }

        System.out.printf("GCD of given numbers is: %d", num2);
    }

}

输出:

GCD of given numbers is: 11

示例 3:查找两个输入(由用户输入)数字的 GCD

在这个例子中,我们使用Scanner从用户获取输入。用户将输入两个数字的值,程序将找到这些输入数字的 GCD。

import java.util.Scanner;
public class GCDExample3 {

    public static void main(String[] args) {

        int num1, num2;

        //Reading the input numbers
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");
        num1 = (int)scanner.nextInt();

        System.out.print("Enter second number:");
        num2 = (int)scanner.nextInt();

        //closing the scanner to avoid memory leaks
        scanner.close();
        while (num1 != num2) {
        	if(num1 > num2)
                num1 = num1 - num2;
            else
                num2 = num2 - num1;
        }

        //displaying the result
        System.out.printf("GCD of given numbers is: %d", num2);
    }

}

输出:

Enter first number:30
Enter second number:250
GCD of given numbers is: 10

下面是几个相关的 java 例子:

  1. Java 程序:找到 factorial 数
  2. Java 程序:显示 Fibonacci 系列
  3. Java 程序:找到三个数字中最大的数字

Java 程序:找到三个数字中最大的一个

原文: https://beginnersbook.com/2017/09/java-program-to-find-largest-of-three-numbers/

在这里,我们将编写两个 java 程序来查找三个数字中最大的程序。 1)使用if-else..if2)使用嵌套的If

要了解这些程序,您应该掌握 Java 中if..else-if语句的知识。如果您是 java 新手,请从核心 Java 教程开始。

示例 1:使用if-else..if查找三个数字中的最大数字

public class JavaExample{

  public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if( num1 >= num2 && num1 >= num3)
          System.out.println(num1+" is the largest Number");

      else if (num2 >= num1 && num2 >= num3)
          System.out.println(num2+" is the largest Number");

      else
          System.out.println(num3+" is the largest Number");
  }
}

输出:

20 is the largest Number

示例 2:使用嵌套if在三个数字中查找最大数字

public class JavaExample{

   public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if(num1 >= num2) {

	  if(num1 >= num3)
		/* This will only execute if conditions given in both
		 * the if blocks are true, which means num1 is greater
		 * than num2 and num3
		 */
		System.out.println(num1+" is the largest Number");
	  else
	        /* This will only execute if the condition in outer if
		 * is true and condition in inner if is false. which
		 * means num1 is grater than num2 but less than num3.
		 * which means num3 is the largest
		 */
		System.out.println(num3+" is the largest Number");
      } 
      else {

	  if(num2 >= num3)
		/* This will execute if the condition in outer if is false
		 * and inner if is true which means num3 is greater than num1
		 * but num2 is greater than num3\. That means num2 is largest
		 */
		System.out.println(num2+" is the largest Number");
	  else
		/* This will execute if the condition in outer if is false
		 * and inner if is false which means num3 is greater than num1
		 * and num2\. That means num3 is largest
		 */
		System.out.println(num3+" is the largest Number");
      }
   }
}

输出:

20 is the largest Number

Java 程序:使用按位 XOR 运算符交换两个数字

原文: https://beginnersbook.com/2017/09/java-program-to-swap-two-numbers-using-bitwise-xor-operator/

这个 java 程序使用按位 XOR 运算符交换两个数字。在通过程序之前,让我们看看什么是按位 XOR 运算符:按位 XOR 比较两个操作数的相应位,如果它们相等则返回 1,如果它们不相等则返回 0。例如:

num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */

num1 ^ num2比较num1num2的相应位,如果它们不相等则生成 1,否则返回 0.在我们的例子中它将返回 29,相当于 00011101

让我们在 Java 程序中写一下:

示例:使用按位运算符交换两个数字

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");
        num1 = scanner.nextInt();
        System.out.print("Enter second number:");
        num2 = scanner.nextInt();
        /* To make you understand, lets assume I am going
         * to enter value of first number as 10 and second 
         * as 5\. Binary equivalent of 10 is 1010 and 5 is
         * 0101
         */

        //num1 becomes 1111 = 15
        num1 = num1 ^ num2;
        //num2 becomes 1010 = 10
        num2 = num1 ^ num2;
        //num1 becomes 0101 = 5
        num1 = num1 ^ num2;
        scanner.close();
        System.out.println("The First number after swapping:"+num1);
        System.out.println("The Second number after swapping:"+num2);
    }
}

输出:

Enter first number:10
Enter second number:5
The First number after swapping:5
The Second number after swapping:10

Java 程序:使用三元运算符查找最小的三个数字

原文: https://beginnersbook.com/2017/09/java-program-to-find-the-smallest-of-three-numbers-using-ternary-operator/

这个 java 程序使用三元运算符找到三个数中最小的一个。让我们看看什么是三元运算符
这个运算符计算一个布尔表达式并根据结果赋值。

variable num1 = (expression) ? value if true : value if false

如果表达式结果为true,则将冒号(:)之前的第一个值分配给变量num1,否则将第二个值分配给num1

示例:使用三元运算符编程以查找三个最小的数字

我们使用三元运算符两次得到最终输出,因为我们分两步完成了比较:
第一步:比较num1num2,并将这两者中最小的一个存储到临时变量temp中。
第二步:比较num3temp得到三个中最小的一个。
如果你愿意,你可以在一个语句中这样做:

result = num3 < (num1 < num2 ? num1:num2) ? num3:(num1 < num2 ? num1:num2);

这是完整的程序:

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
        int num1, num2, num3, result, temp;
        /* Scanner is used for getting user input. 
         * The nextInt() method of scanner reads the
         * integer entered by user.
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter First Number:");
        num1 = scanner.nextInt();
        System.out.println("Enter Second Number:");
        num2 = scanner.nextInt();
        System.out.println("Enter Third Number:");
        num3 = scanner.nextInt();
        scanner.close();

        /* In first step we are comparing only num1 and
         * num2 and storing the smallest number into the
         * temp variable and then comparing the temp and
         * num3 to get final result.
         */

        temp = num1 < num2 ? num1:num2;
        result = num3 < temp ? num3:temp;
        System.out.println("Smallest Number is:"+result);
    }
}

输出:

Enter First Number:
67
Enter Second Number:
7
Enter Third Number:
9
Smallest Number is:7

Java 程序:使用三元运算符查找三个数字中的最大数字

原文: https://beginnersbook.com/2017/09/java-program-to-find-largest-of-three-numbers-using-ternary-operator/

该程序使用三元运算符找到三个数中最大的一个。在完成程序之前,让我们了解什么是三元运算符:
三元运算符计算一个布尔表达式并根据结果赋值。

variable num = (expression) ? value if true : value if false

如果表达式结果为true,则将冒号(:)之前的第一个值赋给变量num,否则将第二个值赋给num

示例:使用三元运算符编程以查找最大数字

在本程序中,我们使用三元运算符两次来比较这三个数字,但是您可以使用三元运算符比较一个语句中的所有三个数字,如下所示:

result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);

但是,如果您发现难以理解,那么请使用它,就像我在下面的示例中所示:

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
        int num1, num2, num3, result, temp;
        /* Scanner is used for getting user input. 
         * The nextInt() method of scanner reads the
         * integer entered by user.
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter First Number:");
        num1 = scanner.nextInt();
        System.out.println("Enter Second Number:");
        num2 = scanner.nextInt();
        System.out.println("Enter Third Number:");
        num3 = scanner.nextInt();
        scanner.close();

        /* In first step we are comparing only num1 and
         * num2 and storing the largest number into the
         * temp variable and then comparing the temp and
         * num3 to get final result.
         */
        temp = num1>num2 ? num1:num2;
        result = num3>temp ? num3:temp;
        System.out.println("Largest Number is:"+result);
    }
}

输出:

Enter First Number:
89
Enter Second Number:
109
Enter Third Number:
8
Largest Number is:109

Java 程序:相加两个二进制数

原文: https://beginnersbook.com/2018/09/java-program-to-add-two-binary-numbers/

在本教程中,我们将 java 程序编写为相加两个二进制数。二进制数系统只有两个符号 0 和 1 所以二进制数只包含 0 和 1。在我们编写相加程序之前,让我们看看我们如何在纸上相加,如下图所示:

Adding binary numbers in Java

示例:在 Java 中相加二进制数

在这个程序中,我们使用Scanner从用户获取输入(用户输入我们需要相加的两个二进制数),然后我们使用while循环逐位相加它们,并将结果存储在一个数组中。

import java.util.Scanner;
public class JavaExample {
   public static void main(String[] args)
   {
	//Two variables to hold two input binary numbers	 
	long b1, b2;
	int i = 0, carry = 0;

	//This is to hold the output binary number
	int[] sum = new int[10];

	//To read the input binary numbers entered by user
	Scanner scanner = new Scanner(System.in);

	//getting first binary number from user
	System.out.print("Enter first binary number: ");
	b1 = scanner.nextLong();
	//getting second binary number from user
	System.out.print("Enter second binary number: ");
	b2 = scanner.nextLong();

	//closing scanner after use to avoid memory leak
	scanner.close();
	while (b1 != 0 || b2 != 0) 
	{
		sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
		carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
		b1 = b1 / 10;
		b2 = b2 / 10;
	}
	if (carry != 0) {
		sum[i++] = carry;
	}
	--i;
	System.out.print("输出: ");
	while (i >= 0) {
		System.out.print(sum[i--]);
	}
	System.out.print("\n");  
   }
}

输出:

Enter first binary number: 11100
Enter second binary number: 10101
输出: 110001

Eclipse IDE 中的相同程序:

Java - Adding two binary numbers

Eclipse 中程序的输出:

Adding binary numbers in Java Output of program

以下是一些相关的 java 示例:

  1. Java 程序:相加两个复数
  2. Java 程序:相加两个数字
  3. Java 程序:相加数十进制数字

Java 程序:打印备用素数

原文: https://beginnersbook.com/2019/04/java-program-to-print-alternate-prime-numbers/

在本教程中,我们将编写一个 Java 程序,以显示备用素数,直到给定值

Java 示例:打印备用素数

在以下示例中,我们有两个用户定义的方法:checkPrime()printAltPrime()

checkPrime()方法检查作为参数传递的数字是否为素数,如果数字为素数,则此方法返回 1,否则返回false

printAltPrime()方法打印备用素数,直到作为参数传递的值。

请阅读注释以了解程序的逻辑。

class JavaExample  
{ 

    //method for checking prime number
    static int checkPrime(int num) 
    { 
	int i, flag = 0; 
	for(i = 2; i<= num / 2; i++) 
	{ 
	   if(num % i == 0) 
	   { 
	       flag = 1; 
	       break; 
	   } 
	} 

	/* If flag value is 0 then the given number num
	 * is a prime number else it is not a prime number
	 */
	if(flag == 0) 
	   return 1; 
	else
	   return 0; 
    } 

    //Method for printing alternate prime numbers
    static void printAltPrime(int n) 
    { 
	/* When the temp value is odd then we are
	 * not printing the prime number and when it is
	 * even then we are printing it, this way we are
	 * displaying alternate prime numbers
	 */
	int temp = 2; 

	for(int num = 2; num <= n-1; num++) 
	{ 
	   //checking each number whether it is prime or not
	   if (checkPrime(num) == 1) 
	   {  
		// if temp is even then only print the prime number
		if (temp % 2 == 0) 
		   System.out.print(num + " "); 

		temp ++; 
	   } 
	} 
    } 

    public static void main(String[] args)  
    { 
	int num = 20; 
	System.out.print("Alternate prime numbers upto " + num+" are: ");  
	printAltPrime(num); 
    } 
}

输出:

Java Program to display alternate prime numbers

相关的 Java 示例

  1. Java 程序:显示前n个素数
  2. Java 程序:检查素数
  3. Java 程序:检查一个数字是否完美平方
  4. Java 程序:查看 Armstrong 数字

Java 程序:打印 1 到n或 1 到 100 的偶数

原文: https://beginnersbook.com/2019/04/java-program-to-print-even-numbers-from-1-to-n-or-1-to-100/

在本教程中,我们将编写一个 Java 程序来显示从 1 到n 的偶数,这意味着如果n的值为 100,则该程序将显示 1 到 100 之间的偶数值。

显示从 1 到 n 的偶数,其中n为 100

在下面的例子中,我们显示从 1 到n的偶数,我们在这里设置的n的值是 100,所以基本上这个程序将打印 1 到 100 之间的偶数。

如果整数(不是分数)可以被 2 整除,这意味着在除以 2 时不产生余数,那么它是偶数。我们在这里使用相同的逻辑来找到偶数。我们循环 1 到n并检查每个值是否可以被 2 整除,如果是,那么我们正在显示它。要理解这个程序,你应该具有 Java for循环if语句的基本知识。

class JavaExample {
   public static void main(String args[]) {
	int n = 100;
	System.out.print("Even Numbers from 1 to "+n+" are: ");
	for (int i = 1; i <= n; i++) {
	   //if number%2 == 0 it means its an even number
	   if (i % 2 == 0) {
		System.out.print(i + " ");
	   }
	}
   }
}

输出:

Even Numbers from 1 to 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 
30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 
78 80 82 84 86 88 90 92 94 96 98 100

相关的 Java 示例

  1. Java 程序:打印 1 到 100 的奇数
  2. Java 程序:检查偶数或奇数
  3. Java 程序:检查一个给定的数字是否是完美平方
  4. Java 程序:找到两个数字的 GCD

Java 程序:打印 1 到n或 1 到 100 的奇数

原文: https://beginnersbook.com/2019/04/java-program-to-print-odd-numbers-from-1-to-n-or-1-to-100/

在这个例子中,我们将编写一个 Java 程序来显示从 1 到n 的奇数,这意味着如果n的值为 100,则程序将显示 1 到 100 之间的奇数。

打印 1 到n的奇数,其中n为 100

在下面的例子中,我们提供了 n的值为 100 ,因此程序将打印从 1 到 100 的奇数。

我们在这个程序中使用的逻辑是我们使用for循环遍历从 1 到n的整数值,我们检查每个值是否% 2 != 0,这意味着我们正在检查它是不是一个奇数。要理解这个程序,你应该具有for循环if语句的基本知识。

class JavaExample {
   public static void main(String args[]) {
	int n = 100;
	System.out.print("Odd Numbers from 1 to "+n+" are: ");
	for (int i = 1; i <= n; i++) {
	   if (i % 2 != 0) {
		System.out.print(i + " ");
	   }
	}
   }
}

输出:

Odd Numbers from 1 to 100 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 
31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 
79 81 83 85 87 89 91 93 95 97 99

相关的 Java 示例

  1. Java 程序:检查偶数或奇数
  2. Java 程序:打印备用素数
  3. Java 程序:检查闰年 ]
  4. Java 程序:打印 Pascals 三角

Java 输入/输出程序

Java 程序:从标准输入读取整数值

原文: https://beginnersbook.com/2017/09/java-program-to-read-integer-value-from-the-standard-input/

在这个程序中,我们将看到如何读取用户输入的整数。Scanner类位于java.util包中。它用于捕获原始类型的输入,如intdouble等和字符串。

示例:用于读取用户输入的数字的程序

我们已导入包java.util.Scanner以使用Scanner。为了读取用户提供的输入,我们首先通过传递System.in作为参数来创建Scanner的对象。然后我们使用Scanner类的nextInt()方法来读取整数。如果您不熟悉 Java 并且不熟悉 java 程序的基础知识,那么请阅读核心 Java 的以下主题:

import java.util.Scanner;

public class Demo {

    public static void main(String[] args) {

        /* This reads the input provided by user
         * using keyboard
         */
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        // This method reads the number provided using keyboard
        int num = scan.nextInt();

        // Closing Scanner after the use
        scan.close();

        // Displaying the number 
        System.out.println("The number entered by user: "+num);
    }
}

输出:

Enter any number: 101
The number entered by user: 101

Java 程序:获取 IP 地址

原文: https://beginnersbook.com/2014/07/java-program-to-get-ip-address/

在这个例子中,我们将看到如何获得系统的 IP 地址。步骤如下:

1)通过调用InetAddress类的getLocalHost()方法获取本地主机地址。

2)通过调用getHostAddress()方法获取 IP 地址。

import java.net.InetAddress;

class GetMyIPAddress
{
   public static void main(String args[]) throws Exception
   {
      /* public static InetAddress getLocalHost()
       * throws UnknownHostException: Returns the address 
       * of the local host. This is achieved by retrieving 
       * the name of the host from the system, then resolving 
       * that name into an InetAddress. Note: The resolved 
       * address may be cached for a short period of time.
       */
      InetAddress myIP=InetAddress.getLocalHost();

      /* public String getHostAddress(): Returns the IP 
       * address string in textual presentation.
       */
      System.out.println("My IP Address is:");
      System.out.println(myIP.getHostAddress());
  }
}

输出:

My IP Address is:
115.242.7.243

参考:

InetAddress javadoc

Java 程序:从用户获取输入

原文: https://beginnersbook.com/2014/07/java-program-to-get-input-from-user/

在本教程中,我们将看到如何接受来自用户的输入。我们使用Scanner类来获取输入。在下面的例子中,我们得到输入字符串,整数和浮点数。为此,我们使用以下方法:

1)public String nextLine():用于获取String输入

2)public int nextInt():用于整数输入

3)public float nextFloat():用于float输入

例:

import java.util.Scanner;

class GetInputData
{
  public static void main(String args[])
  {
     int num;
     float fnum;
     String str;

     Scanner in = new Scanner(System.in);

     //Get input String
     System.out.println("Enter a string: ");
     str = in.nextLine();
     System.out.println("Input String is: "+str);

     //Get input Integer
     System.out.println("Enter an integer: ");
     num = in.nextInt();
     System.out.println("Input Integer is: "+num);

     //Get input float number
     System.out.println("Enter a float number: ");
     fnum = in.nextFloat();
     System.out.println("Input Float number is: "+fnum); 
  }
}

输出:

Enter a string: 
Chaitanya
Input String is: Chaitanya
Enter an integer: 
27
Input Integer is: 27
Enter a float number: 
12.56
Input Float number is: 12.56

参考:

扫描仪 Javadoc

Java 程序:几何计算

Java 程序:计算矩形面积

原文: https://beginnersbook.com/2014/01/java-program-to-calculate-area-of-rectangle/

在本教程中,我们将看到如何计算矩形面积

程序 1:

用户将在程序执行期间提供长度和宽度值,并根据提供的值计算面积。

/**
 * @author: BeginnersBook.com
 * @description: Program to Calculate Area of rectangle
 */
import java.util.Scanner;
class AreaOfRectangle {
   public static void main (String[] args)
   {
	   Scanner scanner = new Scanner(System.in);
	   System.out.println("Enter the length of Rectangle:");
	   double length = scanner.nextDouble();
	   System.out.println("Enter the width of Rectangle:");
	   double width = scanner.nextDouble();
	   //Area = length*width;
	   double area = length*width;
	   System.out.println("Area of Rectangle is:"+area);
   }
}

输出:

Enter the length of Rectangle:
2
Enter the width of Rectangle:
8
Area of Rectangle is:16.0

程序 2:

在上述程序中,将要求用户提供长度和宽度值。如果您不需要用户交互并且只想在程序中指定值,请参阅以下程序。

/**
 * @author: BeginnersBook.com
 * @description: Calculation with no user interaction
 */
class AreaOfRectangle2 {
   public static void main (String[] args)
   {
	   double length = 4.5;
	   double width = 8.0;
	   double area = length*width;
	   System.out.println("Area of Rectangle is:"+area);
   }
}

输出:

Area of Rectangle is:36.0

Java 程序:计算正方形的面积

原文: https://beginnersbook.com/2014/01/java-program-to-calculate-area-of-square/

在本教程中,我们将学习如何计算正方形的面积。以下是两种方法:

1)程序 1:提示用户输入正方形的边长

2)程序 2:在程序的源代码中指定正方形的边长。

计划 1:

/**
 * @author: BeginnersBook.com
 * @description: Program to Calculate Area of square.Program 
 * will prompt user for entering the side of the square.
 */
import java.util.Scanner;
class SquareAreaDemo {
   public static void main (String[] args)
   {
       System.out.println("Enter Side of Square:");
       //Capture the user's input
       Scanner scanner = new Scanner(System.in);
       //Storing the captured value in a variable
       double side = scanner.nextDouble();
       //Area of Square = side*side
       double area = side*side; 
       System.out.println("Area of Square is: "+area);
   }
}

输出:

Enter Side of Square:
2.5
Area of Square is: 6.25

计划 2:

/**
 * @author: BeginnersBook.com
 * @description: Program to Calculate Area of square.
 * No user interaction: Side of square is hard-coded in the
 * program itself.
 */
class SquareAreaDemo2 {
   public static void main (String[] args)
   {
       //Value specified in the program itself
       double side = 4.5;
       //Area of Square = side*side
       double area = side*side; 
       System.out.println("Area of Square is: "+area);
   }
}

输出:

Area of Square is: 20.25

Java 程序:相加两个复数

原文: https://beginnersbook.com/2018/09/java-program-to-add-two-complex-numbers/

复数有两部分 - 实部​​和虚部。在教程中,我们编写 Java 程序相加两个复数。相加复数时,我们将实部和虚部加在一起,如下图所示。

Java Add two complex numbers

示例 - 在 Java 中相加两个复数

在这个程序中,我们有一个类ComplexNumber。在这个类中,我们有两个实例变量realimg来保存复数的实部和虚部。

我们已经声明了一个方法sum()通过将它们的实部和虚部加在一起来相加两个数字

此类的构造函数用于初始化复数。对于例如当我们像这个ComplexNumber temp = new ComplexNumber(0, 0);创建这个类的实例时,它实际上会创建一个复数0 + 0i

public class ComplexNumber{
   //for real and imaginary parts of complex numbers
   double real, img;

   //constructor to initialize the complex number
   ComplexNumber(double r, double i){
	this.real = r;
	this.img = i;
   }

   public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2)
   {
	//creating a temporary complex number to hold the sum of two numbers
        ComplexNumber temp = new ComplexNumber(0, 0);

        temp.real = c1.real + c2.real;
        temp.img = c1.img + c2.img;

        //returning the output complex number
        return temp;
    }
    public static void main(String args[]) {
	ComplexNumber c1 = new ComplexNumber(5.5, 4);
	ComplexNumber c2 = new ComplexNumber(1.2, 3.5);
        ComplexNumber temp = sum(c1, c2);
        System.out.printf("Sum is: "+ temp.real+" + "+ temp.img +"i");
    }
}

输出:

Sum is: 6.7 + 7.5i

屏幕截图:Eclipse IDE 中的相同 Java 程序 -

Java Program to add two complex numbers in Eclipse IDE

Eclipse IDE 中的输出:

Output of adding two complex numbers in Java
以下是一些相关的 java 示例:

    1. Java 程序:找到最大的三个数字
    2. Java 程序:使用Switch Case制作计算器
    3. Java 程序:交换两个数字
    4. C++ 程序:相加两个复数

Java 程序:计算三角面积

原文: https://beginnersbook.com/2014/01/java-program-to-calculate-area-of-triangle/

在这里,我们将看到如何计算三角形的面积。我们将看到以下两个程序:

1)程序 1:提示用户输入三角形的基本宽度和高度。

2)程序 2:无用户交互:程序本身指定了宽度和高度。

计划 1:

/**
 * @author: BeginnersBook.com
 * @description: Program to Calculate area of Triangle in Java
 * with user interaction. Program will prompt user to enter the 
 * base width and height of the triangle.
 */
import java.util.Scanner;
class AreaTriangleDemo {
   public static void main(String args[]) {   
      Scanner scanner = new Scanner(System.in);

      System.out.println("Enter the width of the Triangle:");
      double base = scanner.nextDouble();

      System.out.println("Enter the height of the Triangle:");
      double height = scanner.nextDouble();

      //Area = (width*height)/2
      double area = (base* height)/2;
      System.out.println("Area of Triangle is: " + area);      
   }
}

输出:

Enter the width of the Triangle:
2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0

计划 2:

/**
 * @author: BeginnersBook.com
 * @description: Program to Calculate area of Triangle
 * with no user interaction.
 */
class AreaTriangleDemo2 {
   public static void main(String args[]) {   
      double base = 20.0;
      double height = 110.5;
      double area = (base* height)/2;
      System.out.println("Area of Triangle is: " + area);      
    }
}

输出:

Area of Triangle is: 1105.0

Java 程序:计算圆的面积和周长

原文: https://beginnersbook.com/2014/01/java-program-to-calculate-area-and-circumference-of-circle/

在本教程中,我们将看到如何在 Java 中计算圆的面积和周长。有两种方法可以做到这一点:

1)用户交互:程序将提示用户输入圆的半径

2)没有用户交互:半径值将在程序本身中指定。

计划 1:

/**
 * @author: BeginnersBook.com
 * @description: Program to calculate area and circumference of circle
 * with user interaction. User will be prompt to enter the radius and 
 * the result will be calculated based on the provided radius value.
 */
import java.util.Scanner;
class CircleDemo
{
   static Scanner sc = new Scanner(System.in);
   public static void main(String args[])
   {
      System.out.print("Enter the radius: ");
      /*We are storing the entered radius in double
       * because a user can enter radius in decimals
       */
      double radius = sc.nextDouble();
      //Area = PI*radius*radius
      double area = Math.PI * (radius * radius);
      System.out.println("The area of circle is: " + area);
      //Circumference = 2*PI*radius
      double circumference= Math.PI * 2*radius;
      System.out.println( "The circumference of the circle is:"+circumference) ;
   }
}

输出:

Enter the radius: 1
The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586

程序 2:

/**
 * @author: BeginnersBook.com
 * @description: Program to calculate area and circumference of circle
 * without user interaction. You need to specify the radius value in 
 * program itself.
 */
class CircleDemo2
{
   public static void main(String args[])
   {
      int radius = 3;
      double area = Math.PI * (radius * radius);
      System.out.println("The area of circle is: " + area);
      double circumference= Math.PI * 2*radius;
      System.out.println( "The circumference of the circle is:"+circumference) ;
   }
}

输出:

The area of circle is: 28.274333882308138
The circumference of the circle is:18.84955592153876

Java 排序/搜索程序

Java 程序:升序和降序的冒泡排序

原文: https://beginnersbook.com/2014/07/java-program-for-bubble-sort-in-ascending-descending-order/

在本教程中,我们将看到如何在按升序和降序进行排序。使用冒泡排序算法降序排序。

冒泡排序程序,按升序排序

import java.util.Scanner;

class BubbleSortExample {
  public static void main(String []args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the number of integers to sort:");
    num = input.nextInt();

    int array[] = new int[num];

    System.out.println("Enter " + num + " integers: ");

    for (i = 0; i < num; i++) 
      array[i] = input.nextInt();

    for (i = 0; i < ( num - 1 ); i++) {
      for (j = 0; j < num - i - 1; j++) {
        if (array[j] > array[j+1]) 
        {
           temp = array[j];
           array[j] = array[j+1];
           array[j+1] = temp;
        }
      }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++) 
      System.out.println(array[i]);
  }
}

输出:

Enter the number of integers to sort:
6
Enter 6 integers: 
12
6
78
9
45
08
Sorted list of integers:
6
8
9
12
45
78

冒泡排序程序,按降序排序

为了按降序排序,我们只需要将上面程序中的数组array的逻辑从array[j] > array[j+1]更改为array[j] < array[j+1]。完整代码如下:

import java.util.Scanner;

class BubbleSortExample {
  public static void main(String []args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the number of integers to sort:");
    num = input.nextInt();

    int array[] = new int[num];

    System.out.println("Enter " + num + " integers: ");

    for (i = 0; i < num; i++) 
      array[i] = input.nextInt();

    for (i = 0; i < ( num - 1 ); i++) {
      for (j = 0; j < num - i - 1; j++) {
        if (array[j] < array[j+1]) 
        {
          temp = array[j];
          array[j] = array[j+1];
          array[j+1] = temp;
        }
      }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++) 
      System.out.println(array[i]);
  } 
}

输出:

Enter the number of integers to sort:
6
Enter 6 integers: 
89
12
45
9
56
102
Sorted list of integers:
102
89
56
45
12
9

Java 程序:线性搜索

原文: https://beginnersbook.com/2014/04/java-program-for-linear-search-example/

示例程序:

该程序使用线性搜索算法,在用户输入的所有其他数字中找出数字。

/* Program: Linear Search Example
 * Written by: Chaitanya from beginnersbook.com
 * Input: Number of elements, element's values, value to be searched
 * 输出:Position of the number input by user among other numbers*/
import java.util.Scanner;
class LinearSearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[];
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 
      //Creating array to store the all the numbers
      array = new int[num]; 
      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
        array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();

      for (counter = 0; counter < num; counter++)
      {
         if (array[counter] == item) 
         {
           System.out.println(item+" is present at location "+(counter+1));
           /*Item is found so to stop the search and to come out of the 
            * loop use break statement.*/
           break;
         }
      }
      if (counter == num)
        System.out.println(item + " doesn't exist in array.");
   }
}

输出 1:

Enter number of elements:
6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3

输出 2:

Enter number of elements:
4
Enter 4 integers
11
22
4
5
Enter the search value:
99
99 doesn't exist in array.

Java 程序:执行二分搜索

原文: https://beginnersbook.com/2014/04/java-program-to-perform-b​​inary-search/

在整数列表上执行二分搜索的程序

该程序使用二分搜索算法来在列表中搜索给定元素。

/* Program: Binary Search Example
 * Written by: Chaitanya from beginnersbook.com
 * Input: Number of elements, element's values, value to be searched
 * 输出:Position of the number input by user among other numbers*/
import java.util.Scanner;
class BinarySearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[], first, last, middle;
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 

      //Creating array to store the all the numbers
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
          array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last )
      {
         if ( array[middle] < item )
           first = middle + 1;
         else if ( array[middle] == item )
         {
           System.out.println(item + " found at location " + (middle + 1) + ".");
           break;
         }
         else
         {
             last = middle - 1;
         }
         middle = (first + last)/2;
      }
      if ( first > last )
          System.out.println(item + " is not found.\n");
   }
}

输出 1:

Enter number of elements:
7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

输出 2:

Enter number of elements:
5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.

Java 程序:选择排序

原文: https://beginnersbook.com/2019/04/java-program-for-selection-sorting/

在本教程中,我们将为选择排序编写一个 Java 程序。

选择排序算法如何工作?

选择排序算法的工作原理是将原始数组分成两个子数组:排序子数组和未排序子数组,最初排序的子数组为空。该算法通过从未排序的子数组中重复查找最小元素并将其替换为数组的第一个元素来工作,从而使该数组的一部分成为已排序的子数组。这种情况反复发生,直到整个数组被排序。

Java 程序:在数组上执行选择排序

在下面的示例中,我们定义了一个实现选择排序算法的方法selectionSort()。它从数组中找到最小元素,并将其与数组的第一个元素交换。

我们创建了另一种方法printArr()来显示数组的元素。我们在排序之前和之后调用此方法,以在选择排序之前和之后显示数组元素。

class JavaExample
{
    void selectionSort(int arr[])
    {
        int len = arr.length;

        for (int i = 0; i < len-1; i++)
        {
            // Finding the minimum element in the unsorted part of array
            int min = i;
            for (int j = i+1; j < len; j++)
                if (arr[j] < arr[min])
                    min = j;

            /* Swapping the found minimum element with the first
             * element of the sorted subarray using temp variable
             */
            int temp = arr[min];
            arr[min] = arr[i];
            arr[i] = temp;
        }
    }

    // Displays the array elements
    void printArr(int arr[])
    {
        for (int i=0; i<arr.length; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }

    public static void main(String args[])
    {
        JavaExample obj = new JavaExample();
        int numarr[] = {101,5,18,11,80, 67};

        System.out.print("Original array: ");
        obj.printArr(numarr);

        //calling method for selection sorting
        obj.selectionSort(numarr);

        System.out.print("Sorted array: ");
        obj.printArr(numarr);
    }
}

输出:

Java Selection sort program with example

相关的 Java 示例

  1. Java 程序:对字符串执行冒泡
  2. Java 程序:按升序对数组进行排序
  3. Java 程序:升序和降序冒泡排序
  4. Java 程序:二分搜索
  5. Java 程序:线性搜索

Java 转换程序

Java 程序:八进制到十进制的转换

原文: https://beginnersbook.com/2019/04/java-octal-to-decimal-conversion/

在本文中,我们将看到如何在 Java 中借助示例将八进制转换为十进制。

我们可以通过两种方式将八进制值转换为等效的十进制值:

  1. 使用Integer.parseInt()方法并将基数传递为 8。
  2. 编写我们自己的自定义方法(逻辑)进行转换八进制到十进制。

1. 使用Integer.parseInt()进行 Java 八进制到十进制转换

在下面的示例中,我们将八进制值存储在字符串变量onum中,并使用Integer.parseInt()方法将其转换为十进制值。此方法接受String作为参数,并根据作为参数提供的基本值将其转换为十进制值。

Integer.parseInt()方法中,我们将基数传递为 8,因为八进制数的基值是 8。如果你记得十六进制到十进制转换,我们有传递基数为 16 进行转换。

public class JavaExample{    
   public static void main(String args[]) {
	//octal value
	String onum = "157";

	//octal to decimal using Integer.parseInt()
	int num = Integer.parseInt(onum, 8);

	System.out.println("Decimal equivalent of Octal value 157 is: "+num);
   }
}

输出:

Java octal to decimal conversion example

在上面的例子中,我们对八进制值进行了硬编码,但是如果你想从用户获得八进制值,那么你可以像这样编写逻辑:

import java.util.Scanner;
public class JavaExample{    
   public static void main(String args[]) {
	//octal value
	Scanner scanner = new Scanner(System.in);
	System.out.print("Enter Octal value: ");
	String onum = scanner.nextLine();
	scanner.close();

	//octal to decimal using Integer.parseInt()
	int num = Integer.parseInt(onum, 8);

	System.out.println("Decimal equivalent of value "+onum+" is: "+num);
   }
}

输出:

Enter Octal value: 142
Decimal equivalent of value 142 is: 98

2. 通过编写自定义代码将八进制转换为十进制

在上面的例子中,我们使用Integer.parseInt()方法进行转换,但是我们可以编写自己的逻辑将八进制值转换为等效的十进制值。让我们编写代码:这里我们使用了while循环if..else语句

public class JavaExample{  
   public static int octalToDecimal(int onum){    
	//initializing the decimal number as zero 
	int num = 0;    
	//This value will be used as the power  
	int p = 0;      
	while(true){    
	   if(onum == 0){    
		break;    
	   } else {    
		int temp = onum%10;    
		num += temp*Math.pow(8, p);    
		onum = onum/10;    
		p++;    
	   }    
	}    
	return num;    
   }    
   public static void main(String args[]){        
	System.out.println("Decimal equivalent of octal value 143: "+octalToDecimal(143));       
   }
}

输出:

Java octal to decimal conversion custom logic

Java 程序:十进制到八进制的转换

原文: https://beginnersbook.com/2014/07/java-program-for-decimal-to-octal-conversion/

在本教程中,我们将学习以下两种方法将十进制数转换为等效的八进制数

1)使用预定义的方法Integer.toOctalString(int num)

2)编写我们自己的转换逻辑

import java.util.Scanner;
class DecimalToOctalExample
{
  public static void main(String args[])
  {
    Scanner input = new Scanner( System.in );
    System.out.print("Enter a decimal number : ");
    int num =input.nextInt();

    /* Method 1: 
     * Using predefined method toOctalString(int)
     * Pass the decimal number to this method and
     * it would return the equivalent octal number
     */
    String octalString = Integer.toOctalString(num);
    System.out.println("Method 1: Decimal to octal: " + octalString);

    /* Method 2: 
     * Writing your own logic: Here we will write
     * our own logic for decimal to octal conversion
     */

    // For storing remainder
    int rem;

    // For storing result
    String str=""; 

    // Digits in Octal number system
    char dig[]={'0','1','2','3','4','5','6','7'};

    while(num>0)
    {
       rem=num%8; 
       str=dig[rem]+str; 
       num=num/8;
    }
    System.out.println("Method 2: Decimal to octal: "+str);
  }
}

输出:

Enter a decimal number : 123
Method 1: Decimal to octal: 173
Method 2: Decimal to octal: 173

Java 程序:乘以两个数字

原文: https://beginnersbook.com/2017/09/java-program-to-multiply-two-numbers/

当您开始学习 java 编程时,您在作业中遇到了这些类型的问题。这里我们将看到两个 Java 程序,第一个程序接受两个整数(由用户输入)并显示这些数字的乘积。第二个程序采用任意两个数字(可以是整数或浮点数)并显示结果。

示例 1:读取两个整数并打印它们的产品

该程序要求用户输入两个整数并显示产品。要了解如何使用扫描仪获取用户输入,请检查此程序:程序从系统输入读取整数。

import java.util.Scanner;

public class Demo {

    public static void main(String[] args) {

        /* This reads the input provided by user
         * using keyboard
         */
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter first number: ");

        // This method reads the number provided using keyboard
        int num1 = scan.nextInt();

        System.out.print("Enter second number: ");
        int num2 = scan.nextInt();

        // Closing Scanner after the use
        scan.close();

        // Calculating product of two numbers
        int product = num1*num2;

        // Displaying the multiplication result
        System.out.println("输出: "+product);
    }
}

输出:

Enter first number: 15
Enter second number: 6
输出: 90

示例 2:读取两个整数或浮点数并显示乘法

在上面的程序中,我们只能整数。如果我们想计算两个浮点数的乘积怎么办?此程序允许您输入浮点数并计算产品。

这里我们使用数据类型 double 作为数字,这样你就可以输入整数和浮点数。

import java.util.Scanner;

public class Demo {

    public static void main(String[] args) {

        /* This reads the input provided by user
         * using keyboard
         */
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter first number: ");

        // This method reads the number provided using keyboard
        double num1 = scan.nextDouble();

        System.out.print("Enter second number: ");
        double num2 = scan.nextDouble();

        // Closing Scanner after the use
        scan.close();

        // Calculating product of two numbers
        double product = num1*num2;

        // Displaying the multiplication result
        System.out.println("输出: "+product);
    }
}

输出:

Enter first number: 1.5
Enter second number: 2.5
输出: 3.75

Java 程序:十六进制到十进制的转换

原文: https://beginnersbook.com/2019/04/java-hexadecimal-to-decimal-conversion/

在本指南中,我们将在示例的帮助下,学习如何将十六进制转换为十进制数字。

十六进制到十进制转换示例

我们可以简单地使用Integer.parseInt()方法并将基数传递为 16 以将给定的十六进制数转换为等效的十进制数。

这里我们给出了一个十六进制数hexnum,我们通过使用Integer.parseInt()方法将其转换为十进制数,并将基数传递为 16。

public class JavaExample{  
   public static void main(String args[]){ 
	//given hexadecimal number
	String hexnum = "6F";

	//converting hex to decimal by passing base 16 
	int num = Integer.parseInt(hexnum,16);

	System.out.println("Decimal equivalent of given hex number: "+num);
   }
}

输出:

Java hexadecimal to decimal example

基于用户输入的十六进制到十进制转换

在上面的例子中,我们给出了一个数字。如果我们想要我们可以从用户那里获得输入,然后我们可以使用我们上面使用的相同逻辑将输入的十六进制数转换为十进制数。

import java.util.Scanner;
public class JavaExample{  
   public static void main(String args[]){ 
	Scanner scanner = new Scanner(System.in);
	System.out.print("Enter any hexadecimal number: ");
	String hexnum = scanner.nextLine();
	scanner.close();

	//converting hex to decimal by passing base 16 
	int num = Integer.parseInt(hexnum,16);

	System.out.println("Decimal equivalent of given hex number: "+num);
   }
}

输出:

Java hexadecimal to decimal example user input

使用用户定义的方法的十六进制到十进制转换

这里我们没有使用任何预定义的方法进行转换,我们正在编写自己的逻辑来将给定的十六进制数转换为十进制数。我们在用户定义的方法hexToDecimal()中编写了转换逻辑。此示例还使用StringcharAt()indexOf()方法。

public class JavaExample{    
   public static int hexToDecimal(String hexnum){  
	String hstring = "0123456789ABCDEF";  
	hexnum = hexnum.toUpperCase();  
	int num = 0;  
	for (int i = 0; i < hexnum.length(); i++)  
	{  
		char ch = hexnum.charAt(i);  
		int n = hstring.indexOf(ch);  
		num = 16*num + n;  
	}  
	return num;  
   }  
   public static void main(String args[]){    
	System.out.println("Decimal equivalent of 7A is: "+hexToDecimal("7A"));    
   }
}

输出:

Java hexadecimal to decimal using custom logic

Java 程序:十进制到十六进制的转换

原文: https://beginnersbook.com/2014/07/java-program-to-convert-decimal-to-hexadecimal/

将十进制数转换为十六进制数有以下两种方法:

1)使用Integer类的toHexString()方法

2)通过编写自己的逻辑进行转换,而无需使用任何预定义的方法。

方法 1:使用toHexString()方法的十进制到十六进制转换

import java.util.Scanner;
class DecimalToHexExample
{
    public static void main(String args[])
    {
      Scanner input = new Scanner( System.in );
      System.out.print("Enter a decimal number : ");
      int num =input.nextInt();

      // calling method toHexString()
      String str = Integer.toHexString(num);
      System.out.println("Method 1: Decimal to hexadecimal: "+str);
    }
}

输出:

Enter a decimal number : 123
Method 1: Decimal to hexadecimal: 7b

方法 2:不使用预定义的方法的十进制到十六进制转换

import java.util.Scanner;
class DecimalToHexExample
{
   public static void main(String args[])
   {
     Scanner input = new Scanner( System.in );
     System.out.print("Enter a decimal number : ");
     int num =input.nextInt();

     // For storing remainder
     int rem;

     // For storing result
     String str2=""; 

     // Digits in hexadecimal number system
     char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

     while(num>0)
     {
       rem=num%16; 
       str2=hex[rem]+str2; 
       num=num/16;
     }
     System.out.println("Method 2: Decimal to hexadecimal: "+str2);
  }
}

输出:

Enter a decimal number : 123
Method 2: Decimal to hexadecimal: 7B

Java 程序:二进制到八进制的转换

原文: https://beginnersbook.com/2019/04/java-binary-to-octal-conversion/

在本教程中,我们将看到如何借助示例将二进制数转换为八进制数。

二进制到八进制转换示例

要将二进制数转换为八进制数,我们可以使用Integer.toOctalString()方法,该方法将二进制数作为参数并返回一个字符串,该字符串是传递的二进制数的八进制等效值。

这里我们给出了一个String形式的二进制数,我们首先使用Integer.parseInt()方法将字符串转换为基数 2(二进制数),我们将结果存储在整数bnum中。然后我们将这个二进制数bnum传递给Integer.toOctalString()方法以获取八进制数。

public class JavaExample{  
   public static void main(String args[]){  
	/* To take input from user, import the java.util.Scanner
	 * package and write the following lines
	 * Scanner scanner = new Scanner(System.in);
 	 * System.out.println("Enter the number: ");
	 * int bnum = Integer.parseInt(scanner.nextLine(), 2);
         */
	String number = "10101";
	int bnum = Integer.parseInt(number, 2);
	String ostr = Integer.toOctalString(bnum);
	System.out.println("Octal Value after conversion is: "+ostr);
   }
}

输出:

Java binary to Octal conversion

如评论中所示,如果我们想从用户那里获取二进制数而不是硬编码值,那么我们可以导入java.util.Scanner包并使用以下代码行:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number: ");
int bnum = Integer.parseInt(scanner.nextLine(), 2);

Java 程序:Stringboolean的转换

原文: https://beginnersbook.com/2019/04/java-string-to-boolean-conversion/

在本指南中,我们将在示例的帮助下,看到如何String转换为布尔值

String转换为布尔值时,如果字符串包含值"true"(大小写无关紧要),则转换后的布尔值为true,如果该字符串包含任何其他值,那么转换后的布尔值将为"false"

使用Boolean.parseBoolean()方法将String转换为布尔

这里我们有三个字符串str1str2str3,我们使用Boolean.parseBoolean()方法将它们转换为布尔值,此方法接受String作为参数并返回布尔值truefalse。如果字符串的值为"true"(在任何情况下为大写,小写或混合),则此方法返回true,否则返回false

public class JavaExample{  
   public static void main(String args[]){  
	String str1 = "true";  
	String str2 = "FALSE";  
	String str3 = "Something";  
	boolean bool1=Boolean.parseBoolean(str1);  
	boolean bool2=Boolean.parseBoolean(str2);  
	boolean bool3=Boolean.parseBoolean(str3);  
	System.out.println(bool1);  
	System.out.println(bool2);  
	System.out.println(bool3);  
   }
}

输出:

Java String to Boolean conversion

使用Boolean.valueOf()Stringboolean转换

在这里,我们将看到另一种方法,我们可以使用它来进行字符串到布尔转换。与Boolean.parseBoolean()方法类似,Boolean.valueOf()方法接受字符串作为参数,并返回布尔值truefalse

public class JavaExample{  
   public static void main(String args[]){  
	String str1 = "true";  
	String str2 = "TRue";  
	String str3 = "Something";  
	boolean bool1=Boolean.valueOf(str1);  
	boolean bool2=Boolean.valueOf(str2);  
	boolean bool3=Boolean.valueOf(str3);  
	System.out.println(bool1);  
	System.out.println(bool2);  
	System.out.println(bool3);  
   }
}

输出:

Java String to boolean example

Java 程序:布尔值到String的转换

原文: https://beginnersbook.com/2015/05/java-boolean-to-string/

我们可以通过两种方法将布尔值转换为String

1)**方法 1:使用String.valueOf(boolean b):此方法接受boolean参数并将其转换为等效的String值。

方法声明

public static String valueOf(boolean b)

参数

b - 表示我们要转换的布尔变量

返回

b的字符串表示

boolean boovar = true;
String str = String.valueOf(boovar);

2)**方法 2:使用Boolean.toString(boolean b):此方法与String.valueOf()方法的作用相同。它属于Boolean类,并将指定的boolean转换为String。如果传递的boolean值为true,则返回的字符串将具有"true"值,类似于false,返回的字符串将具有"false"值。

方法声明

public static String toString(boolean b)

参数

b - 表示需要转换的布尔变量

返回

表示传递的布尔值的字符串。

boolean boovar = false;
String str = Boolean.toString(boovar);

示例:将布尔值转换为String

该程序演示了上述两种方法的使用。这里我们有两个布尔变量,我们使用String.valueOf()方法转换其中一个,使用Boolean.toString()方法转换其中一个。

package com.beginnersbook.string;

public class BooleanToString {
    public static void main(String[] args) {

        /* Method 1: using valueOf() method
         * of String class.
         */
        boolean boovar = true;
        String str = String.valueOf(boovar);
        System.out.println("String is: "+str);

        /* Method 2: using toString() method 
         * of Boolean class
         */
        boolean boovar2 = false;
        String str2 = Boolean.toString(boovar2);
        System.out.println("String2 is: "+str2);
    }
}

输出:

String is: true
String2 is: false

Java 程序:intchar的转换

原文: https://beginnersbook.com/2019/04/java-int-to-char-conversion/

在上一个教程中,我们讨论了charint转换。在本指南中,我们将看到如何借助示例将int转换为char

intchar转换示例

要将更高的数据类型转换为更低的数据类型,我们需要进行类型转换。由于int是比char(2 字节)更高的数据类型(4 字节),因此我们需要为转换明确地对int进行类型转换。

//implicit type casting - automatic conversion
char ch = 'A'; // 2 bytes
int num = ch; // 2 bytes to 4 bytes

/* explicit type casting - no automatic conversion
 * because converting higher data type to lower data type
 */
int num = 100; //4 bytes
char ch = (char)num; //4 bytes to 2 bytes

让我们举个例子。

在下面的示例中,我们有一个值为 70 的整数num,我们通过进行类型转换将其转换为char

public class JavaExample{  
   public static void main(String args[]){  
	//integer number
	int num = 70;

	//type casting
	char ch = (char)num;  
	System.out.println(ch);  
   }
}

输出:

Java int to char conversion

Java 程序:charint的转换

原文: https://beginnersbook.com/2019/04/java-char-to-int-conversion/

在本教程中,我们将看到如何借助示例将char转换为int。将字符转换为整数等同于查找给定字符的 ASCII 值(这是一个整数)。

charint隐式类型转换

由于char是与int相比较小的数据类型,因此我们不需要在此处进行显式类型转换。将char值简单赋值给int变量就可以了,编译器会自动将char转换为int,这个过程称为隐式类型转换或类型提升。

在下面的示例中,我们将char值分配给整数变量,而不进行任何类型转换。编译器在这里自动进行转换,这仅适用于我们将较小的数据类型分配给较大的数据类型,否则我们必须进行显式类型转换。

public class JavaExample{  
   public static void main(String args[]){  
	char ch = 'A';
	char ch2 = 'Z';
	int num = ch;
	int num2 = ch2;
	System.out.println("ASCII value of char "+ch+ " is: "+num);
	System.out.println("ASCII value of char "+ch2+ " is: "+num2);
   }
}

输出:

Java char to int conversion example

使用Character.getNumericValue()char转换为int

我们还可以使用Character.getNumericValue(char ch)方法将char转换为int。此方法接受char作为参数,并在转换后返回等效的int(ASCII)值。

这里我们有两个char变量chch2,我们使用Character.getNumericValue()方法将它们转换为整数numnum2

public class JavaExample{  
   public static void main(String args[]){  
	char ch = 'P';
	char ch2 = 'h';

	//conversion using Character.getNumericValue()
	int num = Character.getNumericValue(ch);
	int num2 = Character.getNumericValue(ch2);
	System.out.println("ASCII value of char "+ch+ " is: "+num);
	System.out.println("ASCII value of char "+ch2+ " is: "+num2);
   }
}

输出:

Java convert char to int example

使用Integer.parseInt()方法将char转换为int

这里我们使用Integer.parseInt(String)方法将给定的char转换为int。由于此方法接受字符串参数,因此我们使用String.valueOf()方法将char转换为String,然后将转换后的值传递给方法。

public class JavaExample{  
   public static void main(String args[]){  
	char ch = '9';

	/* Since parseInt() method of Integer class accepts
   	 * String argument only, we must need to convert
	 * the char to String first using the String.valueOf()
	 * method and then we pass the String to the parseInt()
	 * method to convert the char to int
	 */
	int num = Integer.parseInt(String.valueOf(ch));

	System.out.println(num);
   }
}

输出:

Java char to int conversion example

Java 程序:charString的转换

原文: https://beginnersbook.com/2019/04/java-char-to-string-conversion/

在本教程中,我们将在示例的帮助下看到如何将char转换为字符串。

有两种方法可以对字符串进行字符串转换 -

  1. 使用String.valueOf(char ch)方法
  2. 使用Character.toString(char ch)方法

使用String.valueOf(char ch)charString转换

我们可以使用String类的valueOf(char ch)方法将传递的char ch转换为String。此方法接受char作为参数,并返回与参数等效的字符串。

在下面的示例中,我们有一个 char ch,其值为'P',我们使用String.valueOf()方法将其转换为String str。转换后字符串的值为"P"`。

public class JavaExample{  
    public static void main(String args[]){  
	//given char
	char ch = 'P';

	//char to string conversion
	String str = String.valueOf(ch);  

	//displaying the string
	System.out.println("String after conversion is: "+str);    
   }
}

输出:

Java char to String conversion example

使用Character.toString(char ch)char转换为String

我们还可以使用Character类的toString(char ch)方法将传递的char ch转换为String。与String.valueOf(char ch)方法类似,此方法也接受char作为参数并返回等效的String

在下面的示例中,我们使用Character.toString(char ch)方法将char转换为String

public class JavaExample{  
   public static void main(String args[]){  
	// char ch with the value 'Z'
	char ch = 'Z';

	//char to String using toString() method
	String str = Character.toString(ch);  

	//Value of the str after conversion is "Z"
	System.out.println("String after conversion is: "+str);    
   }
}

输出:

Java convert char to String example

Java 程序:longint的转换

原文: https://beginnersbook.com/2019/04/java-long-to-int-conversion/

在本指南中,我们将看到如何通过示例将long转换为int。由于long是比int更大的数据类型,我们需要为转换显式执行类型转换。

longint的示例

在下面的示例中,我们使用显式类型转换将长数据类型转换为int数据类型。这里我们有一个长数据类型的变量lnum,我们将它的值转换为一个int值,我们存储在int数据类型的变量inum中。

public class JavaExample{  
   public static void main(String args[]){  
	long lnum = 1000;  

	//type casting - long to int
	int inum = (int)lnum;  
	System.out.println("Converted int value is: "+inum);  
   }
}

输出:

Java long to int example

使用Long包装类的intValue()方法的longint转换

在下面的示例中,我们有一个Long对象lnum,我们使用Long类的intValue()方法将其转换为int基本类型。

public class JavaExample{  
   public static void main(String args[]){  
	//Long object
	Long lnum = 99L;

	//Converting Long object to int primitive type
	int inum = lnum.intValue();  
	System.out.println("Converted int value: "+inum);  
   }
}

输出:

Java long object to int primitive type

Java 程序:intlong的转换

原文: https://beginnersbook.com/2019/04/java-int-to-long-conversion/

在本教程中,我们将看到如何通过示例将int转换为long

由于int是比long更小的数据类型,因此可以通过简单的赋值将其转换为long。这称为隐式类型转换或类型提升,编译器自动将较小的数据类型转换为较大的数据类型。我们还可以使用Long包装类的valueOf()方法将int转换为long

使用隐式类型转换的intlong转换

在下面的示例中,我们只是将整数数据类型分配给长数据类型。由于整数是一个较小的数据类型而不是long,编译器会自动将int转换为long,这称为类型提升。

public class JavaExample{  
   public static void main(String args[]){  
	int num = 10;  

	/* Implicit type casting, automatic
	 * type conversion by compiler
	 */
	long lnum = num;  
	System.out.println(lnum);  
   }
}

输出:

Java int to long conversion

使用Long.valueOf()方法的intlong转换

在下面的示例中,我们使用Long包装类valueOf()方法将int转换为longvalueOf()方法接受integer作为参数,并在转换后返回long值。

public class JavaExample{  
   public static void main(String args[]){  
	int inum = 99;  
	Long lnum = Long.valueOf(inum);  
	System.out.println("Converted long value is: "+lnum);  
   }
}

输出:

Java int to long conversion using valueOf() method of Long class

Java 程序:检查闰年

原文: https://beginnersbook.com/2017/09/java-program-to-check-leap-year/

在这里,我们将编写一个 java 程序来检查输入年份是否是闰年。在我们看到该程序之前,让我们看看如何确定一年是否是数学上的闰年:
要确定一年是否是闰年,请按以下步骤操作:

  1. 如果年份可被 4 整除,转到步骤 2.否则,转到步骤 5.
  2. 如果年份可以被 100 整除,请转到步骤 3.否则,转到步骤 4.
  3. 如果年份可以整除到 400,转到步骤 4.否则,转到步骤 5.
  4. 年份是闰年(有 366 天)。
  5. 这一年不是闰年(它有 365 天)。

这些步骤的来源

示例:用于检查输入年份是否为跳跃的程序

这里我们使用Scanner类来获取用户的输入,然后我们使用if-else语句编写逻辑来检查闰年。要理解这个程序,你应该具备以下核心 Java 教程的概念:
If-else语句
Java 程序:读取输入数字

import java.util.Scanner;
public class Demo {

    public static void main(String[] args) {

    	int year;
    	Scanner scan = new Scanner(System.in);
    	System.out.println("Enter any Year:");
    	year = scan.nextInt();
    	scan.close();
        boolean isLeap = false;

        if(year % 4 == 0)
        {
            if( year % 100 == 0)
            {
                if ( year % 400 == 0)
                    isLeap = true;
                else
                    isLeap = false;
            }
            else
                isLeap = true;
        }
        else {
            isLeap = false;
        }

        if(isLeap==true)
            System.out.println(year + " is a Leap Year.");
        else
            System.out.println(year + " is not a Leap Year.");
    }
}

输出:

Enter any Year: 
2001
2001 is not a Leap Year.

Java 程序:十进制到二进制的转换

原文: https://beginnersbook.com/2014/07/java-program-to-convert-decimal-to-binary/

将十进制数转换为二进制数有以下三种方法:

1)使用Integer类的toBinaryString()方法

2)通过编写自己的逻辑进行转换,而无需使用任何预定义的方法。

3)使用Stack

方法 1:使用toBinaryString()方法

class DecimalBinaryExample{

    public static void main(String a[]){
    	System.out.println("Binary representation of 124: ");
    	System.out.println(Integer.toBinaryString(124));
        System.out.println("\nBinary representation of 45: ");
        System.out.println(Integer.toBinaryString(45));
        System.out.println("\nBinary representation of 999: ");
        System.out.println(Integer.toBinaryString(999));
    }
}

输出:

Binary representation of 124: 
1111100

Binary representation of 45: 
101101

Binary representation of 999: 
1111100111

方法 2:不使用预定义的方法

class DecimalBinaryExample{

  public void convertBinary(int num){
     int binary[] = new int[40];
     int index = 0;
     while(num > 0){
       binary[index++] = num%2;
       num = num/2;
     }
     for(int i = index-1;i >= 0;i--){
       System.out.print(binary[i]);
     }
  }

  public static void main(String a[]){
     DecimalBinaryExample obj = new DecimalBinaryExample();
     System.out.println("Binary representation of 124: ");
     obj.convertBinary(124);
     System.out.println("\nBinary representation of 45: ");
     obj.convertBinary(45);
     System.out.println("\nBinary representation of 999: ");
     obj.convertBinary(999);
  }
}

输出:

Binary representation of 124: 
1111100
Binary representation of 45: 
101101
Binary representation of 999: 
1111100111

方法 3:使用Stack进行二进制到十进制转换

import java.util.*;
class DecimalBinaryStack
{
  public static void main(String[] args) 
  { 
    Scanner in = new Scanner(System.in);

    // Create Stack object
    Stack<Integer> stack = new Stack<Integer>();

    // User input 
    System.out.println("Enter decimal number: ");
    int num = in.nextInt();

    while (num != 0)
    {
      int d = num % 2;
      stack.push(d);
      num /= 2;
    } 

    System.out.print("\nBinary representation is:");
    while (!(stack.isEmpty() ))
    {
      System.out.print(stack.pop());
    }
    System.out.println();
  }
}

输出:

Enter decimal number: 
999

Binary representation is:1111100111

Java 程序:二进制到十进制的转换

原文: https://beginnersbook.com/2014/07/java-program-for-binary-to-decimal-conversion/

将二进制数转换为十进制数有以下两种方法:

1)使用Integer类的Integer.parseInt()方法

2)通过编写自己的逻辑进行转换,而无需使用任何预定义的方法。

方法 1:使用Integer.parseInt()方法进行二进制到十进制的转换

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       System.out.println("输出: "+Integer.parseInt(binaryString,2));
    }
}

输出:

Enter a binary number: 1101
输出: 13

方法 2:不使用parseInt进行转换

public class Details {

  public int BinaryToDecimal(int binaryNumber){

    int decimal = 0;
    int p = 0;
    while(true){
      if(binaryNumber == 0){
        break;
      } else {
          int temp = binaryNumber%10;
          decimal += temp*Math.pow(2, p);
          binaryNumber = binaryNumber/10;
          p++;
       }
    }
    return decimal;
  }

  public static void main(String args[]){
    Details obj = new Details();
    System.out.println("110 --> "+obj.BinaryToDecimal(110));
    System.out.println("1101 --> "+obj.BinaryToDecimal(1101));
    System.out.println("100 --> "+obj.BinaryToDecimal(100));
    System.out.println("110111 --> "+obj.BinaryToDecimal(110111));
  }
}

输出:

110 --> 6
1101 --> 13
100 --> 4
110111 --> 55

Java 程序:查找字符的 ASCII 值

原文: https://beginnersbook.com/2017/09/java-program-to-find-ascii-value-of-a-character/

ASCII 是用于将英文字符表示为数字的代码,英文字母的每个字母被分配一个从 0 到 127 的数字。例如,大写字母P的 ASCII 代码是 80。
Java 编程中,我们有两种方法可以找到一个字符的 ASCII 值 1)通过为int变量赋一个字符 2)通过将字符的类型转换为int

让我们编写一个程序来了解它是如何工作的:

示例:用于查找字符的 ASCII 代码的程序

public class Demo {

    public static void main(String[] args) {

        char ch = 'P';
        int asciiCode = ch;
        // type casting char as int
        int asciiValue = (int)ch;

        System.out.println("ASCII value of "+ch+" is: " + asciiCode);
        System.out.println("ASCII value of "+ch+" is: " + asciiValue);
    }
}

输出:

ASCII value of P is: 80
ASCII value of P is: 80

Java 程序:Stringint的转换

原文: https://beginnersbook.com/2013/12/how-to-convert-string-to-int-in-java/

在这个教程中,我们将学习如何在 Java 中将String转换为int。如果字符串1,2,3等数字组成,则在将其转换为整数值之前,不能对其执行任何算术运算。在本教程中,我们将看到两种将String转换为int的方法 -

  1. 使用Integer.parseInt(String)方法将字符串转换为int
  2. 使用Integer.valueOf(String)方法将String转换为int

1. 使用Integer.parseInt(String)String转换为int

Integer包装类parseInt()方法将字符串解析为有符号整数。这就是我们进行转换的方式 -

这里我们有一个字符串str,其值为"1234",方法parseInt()str作为参数,并在解析后返回整数值。

String str = "1234";
int inum = Integer.parseInt(str);

让我们看看完整的例子 -

使用Integer.parseInt(String)String转换为int

public class JavaExample{
   public static void main(String args[]){
	String str="123";
	int inum = 100;

	/* converting the string to an int value
	 * ,the value of inum2 would be 123 after
	 * conversion
	 */
	int inum2 = Integer.parseInt(str);

	int sum = inum+inum2;
	System.out.println("Result is: "+sum);
   }
}

输出:

Java convert string to int using pareseInt()

字符串中的所有字符必须是数字,但第一个字符可以是减号'-'。例如:

String str="-1234";
int inum = Integer.parseInt(str);

inum的值为 -1234

如果String对转换无效,Integer.parseInt()将抛出NumberFormatException。例如:

String str="1122ab";
int num = Integer.valueOf(str);

这会抛出NumberFormatException。你会看到像这样的编译错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1122ab"
 at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)

让我们看一下Stringint转换的完整代码。

2. 使用Integer.valueOf(String)String转换为int

Integer.valueOf(String)Integer.parseInt(String)的作用相同。它还将String转换为int值。但是Integer.valueOf()Integer.parseInt()之间存在差异,valueOf(String)方法返回Integer类的对象,而parseInt(String)方法返回原始int值。无论您选择哪种方法,转换的输出都是相同的。这是它的使用方法:

String str="1122";
int inum = Integer.valueOf(str);

inum的值为 1122。

此方法还允许String的第一个字符为减号-

String str="-1122";
int inum = Integer.valueOf(str);

inum的值为 -1122。

parseInt(String)方法类似,当String中的所有字符都不是数字时,它也会抛出NumberFormatException。例如,值为"11aa22"String将引发异常。

让我们看看使用此方法进行转换的完整代码。

使用Integer.valueOf(String)String转换为int

public class JavaExample{
   public static void main(String args[]){
	//String with negative sign
	String str="-234";

	//An int variable
	int inum = 110;

	/* Convert String to int in Java using valueOf() method
	 * the value of variable inum2 would be negative after 
	 * conversion
	 */
	int inum2 = Integer.valueOf(str);

	//Adding up inum and inum2
	int sum = inum+inum2;

	//displaying sum
	System.out.println("Result is: "+sum);
   }
}

输出:

Convert String to int in Java using valueOf()

让我们看一下Stringint转换的另一个有趣的例子。

String转换为带有前导零的int

在这个例子中,我们有一个由带有前导零的数字组成的字符串,我们想对保留前导零的字符串执行算术运算。为此,我们将字符串转换为int并执行算术运算,稍后我们将使用format()方法将输出值转换为字符串。

public class JavaExample{
   public static void main(String args[]){
       String str="00000678";
       /* String to int conversion with leading zeroes
        * the %08 format specifier is used to have 8 digits in
        * the number, this ensures the leading zeroes
        */
       str = String.format("%08d", Integer.parseInt(str)+102);
       System.out.println("Output String: "+str);
   }
}

输出:

Java String to int conversion - leading zeroes example

参考文献:

Java 程序:intString的转换

原文: https://beginnersbook.com/2015/05/java-int-to-string/

在本指南中,我们将学习如何在 Java 中将int转换为字符串。我们可以使用String.valueOf()Integer.toString()方法将int转换为String。我们也可以使用String.format()方法进行转换。

1. 使用String.valueOf()int转换为String

String.valueOf(int i)方法将整数值作为参数,并返回表示int参数的字符串。

方法签名

public static String valueOf(int i)

参数

i - 需要转换为字符串的整数

返回

表示整数参数的字符串

使用String.valueOf()int转换为String

public class JavaExample {
   public static void main(String args[]) {
	int ivar = 111;
	String str = String.valueOf(ivar);
	System.out.println("String is: "+str); 
	//output is: 555111 because the str is a string 
	//and the + would concatenate the 555 and str
	System.out.println(555+str);
   }
}

输出:

Java Int to String conversion

2. 使用Integer.toString()int转换为String

Integer.toString(int i)方法与String.valueOf(int i)方法的作用相同。它属于Integer类,并将指定的整数值转换为String。例如如果传递的值是 101,那么返回的字符串值将是"101"

方法签名

public static String toString(int i)

参数

i - 需要转换的整数

返回

表示整数i的字符串。

示例:

int ivar2 = 200;
String str2 = Integer.toString(ivar2);

使用Integer.toString()intString转换

public class Example {
   public static void main(String args[]) {
        int ivar = 111;
	String str = Integer.toString(ivar);
	System.out.println("String is: "+str);
	//output is: 555111 because the str is a string 
	//and the + would concatenate the 555 and str
	System.out.println(555+str);

	//output is: 666 because ivar is int value and the
        //+ would perform the addition of 555 and ivar
	System.out.println(555+ivar);
   }
}

输出:

String is: 111
555111
666

示例:将int转换为String

该程序演示了如何使用上述方法(String.valueOf()Integer.toString())。这里我们有两个整数变量,我们使用String.valueOf(int i)方法转换其中一个,使用Integer.toString(int i)方法转换其中一个。

public class IntToString {
    public static void main(String[] args) {

        /* Method 1: using valueOf() method
         * of String class.
         */
        int ivar = 111;
        String str = String.valueOf(ivar);
        System.out.println("String is: "+str);

        /* Method 2: using toString() method 
         * of Integer class
         */
        int ivar2 = 200;
        String str2 = Integer.toString(ivar2);
        System.out.println("String2 is: "+str2);
    }
}

输出:

String is: 111
String2 is: 200

3. 用于转换的String.format()方法

public class JavaExample{  
   public static void main(String args[]){  
	int num = 99;  
	String str = String.format("%d",num);  
	System.out.println("hello"+str);  
   }
}

输出:

hello99

Java 程序:Stringdouble的转换

原文: https://beginnersbook.com/2013/12/how-to-convert-string-to-double-in-java/

在本指南中,我们将看到如何在 Java 中将String转换为Double。将String转换为double有三种方法。

  1. 使用Double.parseDouble(String)方法将String转换为Double
  2. 使用Double.valueOf(String)String转换为Double
  3. 使用Double类的构造函数转换为Double - 自 Java 版本 9 以来,不推荐使用构造函数Double(String)

1. 使用Double.parseDouble(String)转换为Double

public static double parseDouble(String str) throws NumberFormatException

此方法返回传递的String参数的双精度表示。如果指定的String str为空,则此方法抛出NullPointerException,如果字符串格式无效,则抛出NumberFormatException。例如,如果字符串是"122.20ab",则此方法将抛出NumberFormatException

String str="122.202";
double dnum = Double.parseDouble(str);

转换后,double类型的变量dnum的值为 122.202。

让我们看一下使用parseDouble(String)方法进行转换的完整示例。

示例 1:使用parseDouble(String)String转换为double

public class JavaExample{
   public static void main(String args[]){
	String str = "122.202";

	/* Convert String to double using 
	 * parseDouble(String) method of Double
	 * wrapper class
	 */
	double dnum = Double.parseDouble(str);

	//displaying the value of variable dnum
	System.out.println(dnum);
   }
}

输出:

Java Convert String to double using parseDouble()

2. 使用Double.valueOf(String)转换为Double

Java 中Double包装类的valueOf()方法与我们在上面 java 示例中看到的parseDouble()方法类似。

String str = "122.111";
double dnum = Double.valueOf(str);

转换后dnum的值为 122.111

让我们看看使用Double.valueOf(String)方法的完整转换示例。

示例 2:使用valueOf(String)String转换为double

public class JavaExample{
   public static void main(String args[]){
	String str = "122.111";

	/* Convert String to double using 
	 * valueOf(String) method of Double
	 * wrapper class
	 */
	double dnum = Double.valueOf(str);

	//displaying the value of variable dnum
	System.out.println(dnum);
   }
}

输出:

Convert String to double in Java using valueOf()

3. 使用Double类的构造函数将String转换为double

注意:自 Java 版本 9 以来,不推荐使用构造函数Double(String)

String str3 = "999.333";
double var3 = new Double(str3);

Double类有一个构造函数,它解析我们在构造函数中传递的String参数,并返回一个等效的double值。

public Double(String s) throws NumberFormatException

使用这个构造函数,我们可以通过传递我们想要转换的String来创建Double类的新对象。

示例 3:使用Double类的构造函数将String转换为double

在这个例子中,我们创建了一个Double类的对象,将String值转换为double值。

public class Example{
   public static void main(String args[]){
       String str3 ="999.333";
       double var3 = new Double(str3);
       System.out.println(var3);
   }
}

输出:

999.333

参考文献:

Java 程序:double到字符串的转换

原文: https://beginnersbook.com/2015/05/java-double-to-string/

java 教程中,我们将学习如何在 Java 中将double转换为字符串。我们可以通过多种方式进行此转换 -

  1. 使用String.valueOf(double)方法将double转换为字符串。
  2. 使用Double包装类toString()方法在 Java 中将double转换为字符串。
  3. 使用String.format()方法将double转换为字符串
  4. 使用DecimalFormat.format()double转换为字符串
  5. 使用StringBufferStringBuilder转换为字符串

1. 使用String.valueOf(double)方法将double转换为字符串

public static String valueOf(double d):我们可以通过调用String类的valueOf()方法将double原始类型转换为String。此方法返回double参数的字符串表示形式。

public class JavaExample{  
   public static void main(String args[]){ 
	//double value
	double dnum = 99.9999;  

	//convert double to string using valueOf() method
	String str = String.valueOf(dnum);  

	//displaying output string after conversion
	System.out.println("My String is: "+str);  
   }
}

输出:

Java Convert double to String

2. 使用Double包装类的toString()方法将double转换为字符串

public String toString( ):这是另一种可用于double转换为String的方法。此方法返回Double对象的字符串表示形式。此对象表示的原始double值将转换为字符串。

public class JavaExample{  
   public static void main(String args[]){ 
	double dnum = -105.556;  

	//double to string conversion using toString()
	String str = Double.toString(dnum);  

	System.out.println("My String is: "+str);
   }
}

输出:

double to string in Java using Double.toString()

3. 使用String.format()方法将double转换为字符串

String.format()方法可用于双字符串转换。

public class JavaExample{  
   public static void main(String args[]){ 
	double dnum = -99.999;  

	String str = String.format("%f", dnum); 

	System.out.println("My String is: "+str);
   }
}

输出:

Java Convert double to string using String.format()

我们可以使用这种方法调整字符串中的小数位数。例如:如果我们在字符串中只需要小数点后两位数,那么我们可以像这样更改代码:

double dnum = -99.999;  
String str = String.format("%.2f", dnum);

此代码的输出将是:My String is: -100.00

这是因为这个方法的double值。

4. 使用DecimalFormat.format()double转换为字符串

String.format()方法类似。要使用它,我们必须在我们的代码中导入包:java.text.DecimalFormat

import java.text.DecimalFormat;
public class JavaExample{  
   public static void main(String args[]){ 
	double dnum = -99.999;  

	/* creating instance of DecimalFormat
	 * #.000 is to have 3 digits after decimal point 
	 * in our output string
	 */
	DecimalFormat df = new DecimalFormat("#.000");

	//conversion
	String str = df.format(dnum);

	//displaying output
	System.out.println("My String is: "+str);
   }
}

输出:

Convert double to string in java using DecimalFormat

5. 使用StringBufferStringBuilderdouble转换为字符串

我们也可以使用StringBufferStringBuilderdouble转换为String。两者的转换步骤相同。步骤如下 -

  1. 创建StringBuffer/StringBuilder实例
  2. 追加double
  3. StringBuffer/StringBuilder转换为String

double -> StringBuffer -> String

public class JavaExample{  
   public static void main(String args[]){ 
	//double value
	double dnum = 89.891;

	//creating instance of StringBuffer
	StringBuffer sb = new StringBuffer();

	//appending the double value to StringBuffer instance
	sb.append(dnum);

	//converting StringBuffer to String
	String str = sb.toString();

	System.out.println("My String is: "+str);
   }
}

输出:

My String is: 89.891

double - > StringBuilder - > String

public class JavaExample{  
   public static void main(String args[]){ 
	//double value
	double dnum = -66.89;

	//creating instance of StringBuilder
	StringBuilder sb = new StringBuilder();

	//appending the double value to StringBuilder instance
	sb.append(dnum);

	//converting StringBuilder to String
	String str = sb.toString();

	System.out.println("My String is: "+str);
   }
}

输出:

Java Convert double to String using StringBuffer and StringBuilder

Java 程序:字符串到long的转换

原文: https://beginnersbook.com/2013/12/how-to-convert-string-to-long-in-java/

在本教程中,我们将看到如何在 Java 中将String转换为long。将String转换为long值有三种方法。

1. 使用Long.parseLong(String)String转换为long

Long.parseLong(String):字符串中的所有字符必须是除第一个字符外的数字,可以是数字或减号-。例如 - 允许long var = Long.parseInt("-123"); ,转换后的var值为 -123。

使用Long.parseLong(String)String转换为long

在此示例中,字符串str2在开头具有减号'-',这就是变量num2的值为负的原因。

public class JavaExample {
    public static void main(String[] args)
    {
	String str = "21111";
	String str2 = "-11111";

	//Conversion using parseLong(String) method
	long num = Long.parseLong(str);
	long num2 = Long.parseLong(str2);
	System.out.println(num+num2);		
    }
}

输出:

Java String to Long conversion

2. 使用Long.valueOf(String)String转换为long

Long.valueOf(String):将String转换为long值。与parseLong(String)方法类似,此方法还允许减号'-'作为String中的第一个字符。

使用Long.valueOf(String)String转换为long

public class Example {
   public static void main(String[] args)
   {
       String str = "11111";
       String str2 = "88888";
       //Conversion using valueOf(String) method
       long num = Long.valueOf(str);
       long num2 = Long.valueOf(str2);
       System.out.println(num+num2);		
   }
}

输出:

99999

3. 使用Long类的构造函数将String转换为long

Long(String s)构造函数Long类有一个构造函数,它允许String参数并创建一个新的Long对象,表示等效long值中的指定字符串。该字符串将以parseLong(String)方法用于基数 10 的方式完全转换为long值。

使用new Long(String)String转换为long

public class Example {
   public static void main(String[] args)
   {
       String str = "10000";
       String str2 = "22222";
       //Conversion using Long(String s) constructor
       long num = new Long(str);
       long num2 = new Long(str2);
       System.out.println(num*num2);		
   }
}

输出:

222220000

Java 程序:long到字符串的转换

原文: https://beginnersbook.com/2015/05/java-long-to-string/

可以使用以下任何方法将long值转换为String

1)方法 1:使用String.valueOf(long l):此方法将long值作为参数并返回它的字符串表示。

方法声明

public static String valueOf(long l)

参数

l - 我们要转换的long

返回

long l的字符串表示

long lvar = 123;
String str = String.valueOf(lvar);

**2)方法 2:使用Long.toString(long l):此方法与String.valueOf(long)方法的作用相同。它返回表示我们传递给此方法的long值的字符串。对于例如如果传递的值是 1202,那么返回的字符串将是"1202"

方法声明

public static String toString(long l)

参数

l - 这表示我们作为参数传递给方法的long值。

返回

表示传递的long值的字符串。

long lvar2 = 200;
String str2 = Long.toString(lvar2);

示例:将long转换为String

该程序演示了上述两种方法的使用。这里我们有两个long变量(lvarlvar2),我们使用String.valueOf(long l)方法转换其中一个,使用Long.toString(long l)方法转换其中一个。

package com.beginnersbook.string;

public class LongToString {
    public static void main(String[] args) {

        /* Method 1: using valueOf() method
         * of String class.
         */
        long lvar = 123;
        String str = String.valueOf(lvar);
        System.out.println("String is: "+str);

        /* Method 2: using toString() method 
         * of Long class
         */
        long lvar2 = 200;
        String str2 = Long.toString(lvar2);
        System.out.println("String2 is: "+str2);
    }
}

输出:

String is: 123
String2 is: 200

其他 Java 程序

Java 程序:使用Switch Case检查元音或辅音

原文: https://beginnersbook.com/2017/09/java-program-to-check-vowel-and-consonant-using-switch-case/

字母AEIOU(小写和大写)被称为元音,其余的字母表称为辅音。在这里,我们将编写一个 java 程序,使用 Java 中的 Switch Case检查输入字符是元音还是辅音

如果您是 java 新手,请参阅 Java 教程以开始学习基础知识

示例:使用Switch Case检查元音或辅音的程序

在这个程序中,我们没有故意使用break语句,因此如果用户输入任何元音,程序将继续执行所有后续情况,直到达到Case 'U'并且我们正在设置布尔变量的值为true。通过这种方式,我们可以识别用户输入的字母是否为元音。

import java.util.Scanner;
class JavaExample
{
   public static void main(String[ ] arg)
   {
	boolean isVowel=false;;
	Scanner scanner=new Scanner(System.in);
	System.out.println("Enter a character : ");
	char ch=scanner.next().charAt(0); 
	scanner.close();
	switch(ch)
	{
	   case 'a' :
	   case 'e' :
    	   case 'i' :
	   case 'o' :
	   case 'u' :
	   case 'A' :
	   case 'E' :
	   case 'I' :
	   case 'O' :
	   case 'U' : isVowel = true;
	}
	if(isVowel == true) {
	   System.out.println(ch+" is  a Vowel");
	}
	else {
	   if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
		System.out.println(ch+" is a Consonant");
	   else
		System.out.println("Input is not an alphabet");		
        }
   }
}

输出 1:

Enter a character : 
A
A is  a Vowel

输出 2:

Enter a character : 
P
P is a Consonant

输出 3:

Enter a character : 
9
Input is not an alphabet

Java 程序:打印 Floyd 三角形

原文: https://beginnersbook.com/2014/04/java-program-to-print-floyds-triangle-example/

示例程序:

该程序将提示用户输入行数,并根据输入,打印具有相同行数的 Floyd 三角形

/* Program: It Prints Floyd's triangle based on user inputs
 * Written by: Chaitanya from beginnersbook.com
 * Input: Number of rows
 * 输出: floyd's triangle*/
import java.util.Scanner;
class FloydTriangleExample
{
    public static void main(String args[])
    {
       int rows, number = 1, counter, j;
       //To get the user's input
       Scanner input = new Scanner(System.in);
       System.out.println("Enter the number of rows for floyd's triangle:");
       //Copying user input into an integer variable named rows
       rows = input.nextInt();
       System.out.println("Floyd's triangle");
       System.out.println("****************");
       for ( counter = 1 ; counter <= rows ; counter++ )
       {
           for ( j = 1 ; j <= counter ; j++ )
           {
                System.out.print(number+" ");
                //Incrementing the number value
                number++;
           }
           //For new line
           System.out.println();
       }
   }
}

输出:

Enter the number of rows for floyd's triangle:
6
Floyd's triangle
****************

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21

Java 程序:打印 Pascal 三角形

原文: https://beginnersbook.com/2019/02/java-program-to-print-pascal-triangle/

在本教程中,我们将编写一个 java 程序来打印 Pascal 三角

示例:打印 Pascal 三角

在此程序中,要求用户输入行数,并根据输入,使用输入的行数打印 pascal 三角形。

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample {
    static int fact(int num) {
	int factorial;

	for(factorial = 1; num > 1; num--){
		factorial *= num;
	}
	return factorial;
    }
    static int ncr(int n,int r) {
	return fact(n) / ( fact(n-r) * fact(r) );
    }
    public static void main(String args[]){
	int rows, i, j;

	//getting number of rows from user
	System.out.println("Enter number of rows:");
	Scanner scanner = new Scanner(System.in);
	rows = scanner.nextInt();
	scanner.close();

	System.out.println("Pascal Triangle:");
	for(i = 0; i < rows; i++) {
		for(j = 0; j < rows-i; j++){
			System.out.print(" ");
		}
		for(j = 0; j <= i; j++){
			System.out.print(" "+ncr(i, j));
		}
		System.out.println();
 	}
    }
}

输出:

Java Program to print Pascal Triangle

相关的 Java 示例

  1. Java 程序:找到一个数字的平方根
  2. Java 程序:检查一个数字是否完美正方
  3. Java 程序:提取来自输入数字的数字
  4. Java 程序:使用switch-case制作计算器

Java 程序:使用循环显示 Fibonacci 序列

原文: https://beginnersbook.com/2017/09/java-program-to-display-fibonacci-series-using-loops/

Fibonacci 序列是一序列数字,其中数字是前两个数字的总和。从 0 和 1 开始,序列变为0,1,1,2,3,5,8,13,21等。在这里,我们将编写三个程序来打印斐波纳契序列 1)使用for循环 2)使用while循环 3)基于用户输入的数字

要理解这些程序,你应该拥有for循环while循环的知识。

如果您是 java 新手,请参考 java 编程教程开始学习基础知识。

示例 1:使用for循环打印斐波纳契序列

public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        for (int i = 1; i <= count; ++i)
        {
            System.out.print(num1+" ");

            /* On each iteration, we are assigning second number
             * to the first number and assigning the sum of last two
             * numbers to the second number
             */
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
        }
    }
}

输出:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

示例 2:使用while循环显示 Fibonacci 序列

public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

输出:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

示例 3:基于用户输入显示斐波那契序列

该程序根据用户输入的数字显示顺序。例如 - 如果用户输入 10,则此程序显示 10 个数字的序列。

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int count, num1 = 0, num2 = 1;
        System.out.println("How may numbers you want in the sequence:");
        Scanner scanner = new Scanner(System.in);
        count = scanner.nextInt();
        scanner.close();
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

输出:

How may numbers you want in the sequence:
6
Fibonacci Series of 6 numbers:0 1 1 2 3 5

查看这些相关的 Java 程序:

  1. Java 程序:寻找因子
  2. Java 程序:检查素数

Java 程序:使用ForWhile循环查找阶乘

原文: https://beginnersbook.com/2017/09/java-program-to-find-factorial-using-for-and-while-loop/

我们将编写三个 java 程序来查找数字的阶乘。 1)使用for循环 2)使用while循环 3)找到用户输入的数字的阶乘。在完成程序之前,让我们理解什么是阶乘:数字n的因子表示为n!n!的值表示为:1 * 2 * 3 * ... * (n-1) * n

我们在程序中使用循环实现了相同的逻辑。要了解这些程序,您应该具备以下 java 教程主题的基本知识:

示例:使用for循环查找阶乘

public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number = 5;
        long fact = 1;
        for(int i = 1; i <= number; i++)
        {
            fact = fact * i;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}

输出:

Factorial of 5 is: 120

示例 2:使用while循环查找阶乘

public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number = 5;
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}

输出:

Factorial of 5 is: 120

示例 3:查找用户输入的数字的阶乘

程序使用while循环查找输入数的阶乘。

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number;
        System.out.println("Enter the number: ");
        Scanner scanner = new Scanner(System.in);
        number = scanner.nextInt();
        scanner.close();
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}

输出:

Enter the number: 
6
Factorial of 6 is: 720

Java 程序:使用Switch Case制作计算器

原文: https://beginnersbook.com/2017/09/java-program-to-make-a-calculator-using-switch-case/

在本程序中,我们正在制作一个简单的计算器,根据用户输入执行加法,减法,乘法和除法。程序获取两个数字的值(由用户输入),然后要求用户输入操作(+-*/),根据输入程序使用对输入的数字执行所选操作switch-case

如果您是 java 新手,请参阅 Java 教程,从基础开始学习 java 编程。

示例:使用的switch case编写计算器的程序

import java.util.Scanner;

public class JavaExample {

    public static void main(String[] args) {

    	double num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");

        /* We are using data type double so that user
         * can enter integer as well as floating point
         * value
         */
        num1 = scanner.nextDouble();
        System.out.print("Enter second number:");
        num2 = scanner.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        scanner.close();
        double output;

        switch(operator)
        {
            case '+':
            	output = num1 + num2;
                break;

            case '-':
            	output = num1 - num2;
                break;

            case '*':
            	output = num1 * num2;
                break;

            case '/':
            	output = num1 / num2;
                break;

            /* If user enters any other operator or char apart from
             * +, -, * and /, then display an error message to user
             * 
             */
            default:
                System.out.printf("You have entered wrong operator");
                return;
        }

        System.out.println(num1+" "+operator+" "+num2+": "+output);
    }
}

输出:

Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0

Java 程序:计算和显示学生成绩

原文: https://beginnersbook.com/2017/09/java-program-to-calculate-and-display-student-grades/

该程序根据用户在每个科目中输入的标记计算学生的成绩。程序根据此逻辑打印等级。
如果标记的平均值>= 80则打印等级'A'
如果平均值< 80>= 60则打印等级'B'
如果平均值< 60>= 40然后打印等级'C'
否则打印等级'D'

要理解本程序,您应该具备以下 Java 概念的知识:

示例:显示学生成绩的程序

import java.util.Scanner;

public class JavaExample
{
    public static void main(String args[])
    {
    	/* This program assumes that the student has 6 subjects,
    	 * thats why I have created the array of size 6\. You can
    	 * change this as per the requirement.
    	 */
        int marks[] = new int[6];
        int i;
        float total=0, avg;
        Scanner scanner = new Scanner(System.in);

        for(i=0; i<6; i++) { 
           System.out.print("Enter Marks of Subject"+(i+1)+":");
           marks[i] = scanner.nextInt();
           total = total + marks[i];
        }
        scanner.close();
        //Calculating average here
        avg = total/6;
        System.out.print("The student Grade is: ");
        if(avg>=80)
        {
            System.out.print("A");
        }
        else if(avg>=60 && avg<80)
        {
           System.out.print("B");
        } 
        else if(avg>=40 && avg<60)
        {
            System.out.print("C");
        }
        else
        {
            System.out.print("D");
        }
    }
}

输出:

Enter Marks of Subject1:40
Enter Marks of Subject2:80
Enter Marks of Subject3:80
Enter Marks of Subject4:40
Enter Marks of Subject5:60
Enter Marks of Subject6:60
The student Grade is: B

Java 程序:使用方法重载执行算术运算

原文: https://beginnersbook.com/2017/09/java-program-to-perform-arithmetic-operation-using-method-overloading/

该程序使用方法重载查找两个,三个和四个数字的总和。这里我们有三个具有相同名称add()的方法,这意味着我们正在重载此方法。根据我们在调用add方法时传递的参数数量,将确定将调用哪个方法。

要了解这个程序,你应该具备以下核心 Java 主题的知识:
Java 方法重载

示例:使用“方法重载”查找多个数字之和的程序

首先,add()方法有两个参数,这意味着当我们在调用add()方法时传递两个数字时,将调用此方法。类似地,当我们传递三个和四个参数时,将分别调用第二个和第三个add方法。

public class JavaExample
{
    int add(int num1, int num2)
    {
        return num1+num2;
    }
    int add(int num1, int num2, int num3)
    {
        return num1+num2+num3;
    }
    int add(int num1, int num2, int num3, int num4)
    {
        return num1+num2+num3+num4;
    }
    public static void main(String[] args) 
    {    
    	JavaExample obj = new JavaExample();
    	//This will call the first add method
        System.out.println("Sum of two numbers: "+obj.add(10, 20));
        //This will call second add method
        System.out.println("Sum of three numbers: "+obj.add(10, 20, 30));
        //This will call third add method
        System.out.println("Sum of four numbers: "+obj.add(1,  2, 3, 4));
    }
}

输出:

Sum of two numbers: 30
Sum of three numbers: 60
Sum of four numbers: 10

Java 程序:使用方法重载查找几何图形的面积

原文: https://beginnersbook.com/2017/09/java-program-to-find-area-of-geometric-figures-using-method-overloading/

该程序使用方法重载找到正方形,矩形和圆形的面积。在这个程序中,我们有三个同名的方法area(),这意味着我们正在重载area()方法。通过面积方法的三种不同实现,我们计算方形,矩形和圆形的面积。

要理解这个程序,你应该具备以下核心 Java 主题的知识:
Java 中的方法重载

示例:使用方法重载编程以查找方形,矩形和圆的面积

class JavaExample
{
    void calculateArea(float x)
    {
        System.out.println("Area of the square: "+x*x+" sq units");
    }
    void calculateArea(float x, float y)
    {
        System.out.println("Area of the rectangle: "+x*y+" sq units");
    }
    void calculateArea(double r)
    {
        double area = 3.14*r*r;
        System.out.println("Area of the circle: "+area+" sq units");
    }
    public static void main(String args[]){
        JavaExample obj = new JavaExample();

        /* This statement will call the first area() method
         * because we are passing only one argument with
         * the "f" suffix. f is used to denote the float numbers
         * 
         */
	 obj.calculateArea(6.1f);

	 /* This will call the second method because we are passing 
	  * two arguments and only second method has two arguments
	  */
	 obj.calculateArea(10,22);

	 /* This will call the second method because we have not suffixed
	  * the value with "f" when we do not suffix a float value with f 
	  * then it is considered as type double.
	  */
	 obj.calculateArea(6.1);
    }
}

输出:

Area of the square: 37.21 sq units
Area of the rectangle: 220.0 sq units
Area of the circle: 116.8394 sq units

标签:Java,String,示例,int,System,out,public,BeginnersBook
From: https://www.cnblogs.com/apachecn/p/18500091

相关文章

  • BeginnersBook-Java-集合教程-一-
    BeginnersBookJava集合教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0如何在Java中对ArrayList进行排序原文:https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/在本教程中,我们分享了对ArrayList<String>和ArrayList<Integer>进行排序的示例。另请阅......
  • BeginnersBook-Java-IO-教程-一-
    BeginnersBookJavaIO教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0如何在Java中创建文件原文:https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/在本教程中,我们将了解如何使用createNewFile()方法在Java中创建文件。如果文件在指定位置不存在并且......
  • BeginnersBook-C-语言示例-一-
    BeginnersBookC语言示例(一)原文:BeginnersBook协议:CCBY-NC-SA4.0C程序:检查阿姆斯特朗数原文:https://beginnersbook.com/2014/06/c-program-to-check-armstrong-number/如果数字的各位的立方和等于数字本身,则将数字称为阿姆斯特朗数。在下面的C程序中,我们检查输入的......
  • BeginnersBook-C---教程-一-
    BeginnersBookC++教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0C++中的for循环原文:https://beginnersbook.com/2017/08/cpp-for-loop/循环用于重复执行语句块,直到满足特定条件。例如,当您显示从1到100的数字时,您可能希望将变量的值设置为1并将其显示100次,在每......
  • HowToDoInJava-Java-教程-二-
    HowToDoInJavaJava教程(二)原文:HowToDoInJava协议:CCBY-NC-SA4.0JVM内存模型/结构和组件原文:https://howtodoinjava.com/java/garbage-collection/jvm-memory-model-structure-and-components/每当执行Java程序时,都会保留一个单独的存储区,用于存储应用程序代码的各......
  • BeginnersBook-Servlet-教程-一-
    BeginnersBookServlet教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0项目的web.xml文件中的welcome-file-list标签原文:https://beginnersbook.com/2014/04/welcome-file-list-in-web-xml/你有没见过web.xml文件中的<welcome-file-list>标签并想知道它是什么?在本文中,我将......
  • BeginnersBook-Perl-教程-一-
    BeginnersBookPerl教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0Perl-列表和数组原文:https://beginnersbook.com/2017/05/perl-lists-and-arrays/在Perl中,人们可以交替使用术语列表和数组,但是存在差异。列表是数据(标量值的有序集合),数组是保存列表的变量。如何定......
  • StudyTonight-Java-中文教程-六-
    StudyTonightJava中文教程(六)原文:StudyTonight协议:CCBY-NC-SA4.0JavaCharacter.isLetter(char)方法原文:https://www.studytonight.com/java-wrapper-class/java-character-isletterchar-ch-methodJavaisLetter(charch)方法是Character类的一部分。此方法用于检查指......
  • StudyTonight-Java-中文教程-二-
    StudyTonightJava中文教程(二)原文:StudyTonight协议:CCBY-NC-SA4.0JavaFloat类原文:https://www.studytonight.com/java/float-class.phpFloat类将基元类型的浮点值包装在对象中。Float类型的对象包含一个类型为浮点的字段。此外,此类提供了几种将浮点转换为字符串和将......
  • HowToDoInJava-其它教程-2-二-
    HowToDoInJava其它教程2(二)原文:HowToDoInJava协议:CCBY-NC-SA4.0Java核心面试问题–第2部分原文:https://howtodoinjava.com/interview-questions/core-java-interview-questions-series-part-2/在Java面试问题系列:第1部分中,我们讨论了面试官通常问的一些重要......