我们如何使用 println 打印 (n +nn +nnn) 这段代码?

how can we print (n +nn +nnn) using println for this code?

int n; 
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
n = in .nextInt();
System.out.println(n " + " nn ); //this is not working

如何使用 println 进行打印

请将您的代码块格式化为代码。

如果你想像 if

那样打印两次相同的值
int n = 5;
System.out.println(String.valueOf(n) + "+" + String.valueOf(n) + String.valueOf(n);

这将打印 5 + 55

if you want to print the double of n then:
System.out.println(String.valueOf(n) + " + " + n*2;

这将打印 5 + 10

但我不确定您期望的结果是什么

这样的事情可能会有所帮助

n = in .nextInt();
for(int i=1;i<=n;i++){
    for(int j=1;j<=i;j++){
         System.out.print("n");
    }
if(i!=n) {
    System.out.print("+");
}
}

输出::

if input =3
Output => n+nn+nnn

if input=5
output => n+nn+nnn+nnnn+nnnnn

是这样的吗?

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Input number: ");
        String n = in.nextLine();
        if (n.matches("[0-9]+")) {
            System.out.println(n + " + " + n + n + " + " + n + n + n + " = "
                    + (Integer.parseInt(n) + Integer.parseInt(n + n) + Integer.parseInt(n + n + n)));
        } else {
            System.out.println("Error: invalid input.");
        }
    }
}

样本运行-1:

Input number: 5
5 + 55 + 555 = 615

样本运行-2:

Input number: 1
1 + 11 + 111 = 123

样本运行-3:

Input number: a
Error: invalid input.

如果你想打印n+nn+nnn的模式,你可以考虑下面的代码

Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
String n = in.nextLine();
String output = "";
for (int i = 1; i <= 3; i++) {
 output += Stream.generate(() -> "" + n).limit(i).collect(Collectors.joining()) + "+";
}
System.out.println(output.substring(0, output.length() - 1));

输出:

Input number: 5
5+55+555
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("Type your number : ");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        String x=String.valueOf(n);
        System.out.println(x+ " + "+ x+x +" + " +x+x+x+ " = "+ ((Integer.parseInt(x))+(Integer.parseInt(x+x))+ (Integer.parseInt(x+x+x))));

    }
}

输出:(数字 = 5 的示例)

Type your number : 5

5 + 55 + 555 = 615

好吧,这是另一种略有不同的选择。

  • n,要重复的数字
  • k,重复次数
  • 调用 successiveSum(n,k)
successiveSum(1,3);
successiveSum(5,3);
successiveSum(1,4);

版画

1 + 11 + 111  = 123
5 + 55 + 555  = 615
1 + 11 + 111 + 1111  = 1234

方法。

它的工作原理是将数字乘以 10,然后加上 n。

public static void successiveSum(int n, int k) {
   int sum = 0;
   int nextNumb = 0;
   String s = "";
   for (int i = 0; i < k; i++) {
       nextNumb = nextNumb * 10 + n;
       s = s + nextNumb + " + ";
       sum += nextNumb;
   }
   // remove the last "+ " of the string.
   System.out.println(s.substring(0,s.length()-2) + " = " + sum);
}