我们如何使用println为该代码打印(n+nn+nnn)


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 打印

类似的东西?

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.

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

如果你想像一样打印两次相同的值

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

如果你想打印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);
}

最新更新