繁体   English   中英

分隔三位数 integer 的数字

[英]Separating the digits of a three-digit integer

对于我的 APCS class,我的任务是获取用户输入的三位数,并在单独的行中按顺序打印每个数字。 我的代码工作正常:

import java.util.Scanner;
public class threeDigits
{
    public static void main (String [] args ){
        System.out.println("Give me a three digit integer and I will print out each individual digit");
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        int digit1 = number / 100;
        int digit2 = (number % 100)/10;
        int digit3 = number % 10;
        System.out.println(digit1);
        System.out.println(digit2);
        System.out.println(digit3);
    }
}

我想知道的是是否有更好、更简单的方法来获得相同的结果,或者这是否是最好的方法。 即使这是获得结果的最快捷方式,我也希望看到做同样事情的其他方法,而不是为了成绩而交,而是作为一种学习经验。

替代解决方案:

首先输入一个整数并将其转换为String然后遍历String

     public static void main (String [] args ) {
        System.out.println("Give me a three digit integer and I will print out each individual digit");
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        String str = Integer.toString(number);
        for(int i=0; i<str.length(); i++){
            System.out.println(str.charAt(i));
        }
    }

如果允许使用Java 8和内置方法,另一种解决方案是将数字的字符作为String迭代并使用forEach打印。

int number = 12345;
String.valueOf(number).chars().map(Character::getNumericValue).forEach(System.out::println);
// or String.valueOf(number).chars().forEach(c -> System.out.println((char) c));

一种方法是将数字作为字符串读取,并循环遍历字符:

import java.util.Scanner;
public class ThreeDigits
{
    public static void main (String [] args ){
        System.out.println("Give me a three digit integer and I will print out each individual digit");
        Scanner input = new Scanner(System.in);
        String number = input.next();

        for(char c : number.toCharArray())
            System.out.println(c);
    }
}

一个很好的解决方案是使用堆栈。

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

    if(num<0)
        num*=-1;

    Stack<Integer> stack = new Stack<Integer>();
    while (num != 0)
    {
        stack.push(num%10);
        num/=10;
    }
    int count=1;
    while(!stack.isEmpty())
    {
        System.out.println("digit" + count + ": " + stack.pop());
        count++;
    }
}

别忘了导入它。

import java.util.Stack;

import java.util.Scanner;

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

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        int iter = n, sum = 0;

        while(iter > 0) {
            sum = sum + iter;
            iter--;
        }

        System.out.println("The sum from 1 to " + n + " is " + sum + ".");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM