gpt4 book ai didi

java - 计算器,无法按我想要的方式打印出来

转载 作者:行者123 更新时间:2023-12-01 12:00:57 27 4
gpt4 key购买 nike

这是我的作业。但是,我无法让结果发挥作用。我希望它打印出来为:

> 2*7*6
2
* 7
----
14
* 6
----
84

等等。我希望无论我输入多少个数字,代码都能正常工作。这是到目前为止我的代码;

public static int add(int a, int b) {
return a + b;
}

public static int sub(int a, int b) {
return a - b;
}

public static int multiply(int a, int b) {
return a * b;
}

public static void main(String[] args)
{

Scanner in = new Scanner(System.in);

System.out.print("(ex. 8*2*6): ");
String amount = in.nextLine();

if ( amount.contains("+") ) {
String[] parts = amount.split("\\+");
} else if ( amount.contains("-") ) {
String[] parts = amount.split("\\-");
} else if ( amount.contains("*") ) {
String[] parts = amount.split("\\*");
int[] results = new int[parts.length];

// Convert from string to integer
for (int i = 0; i < parts.length; i++) {
try {
results[i] = Integer.parseInt(parts[i]);
} catch (NumberFormatException nfe) {};
}

// Print result
int counter = 1;
for (int i = 0; i <= results.length; i++) {
if ( i == 0) {
System.out.println(" " + results[i]);
System.out.println("* " + results[counter]);
System.out.println("----");
int total = multiply(results[i], results[counter]);
System.out.println(" " + total);
} else if ( i > 1 ) {
System.out.println("* " + results[i]);
System.out.println("----");
System.out.println(" " + multiply(results[i], results[counter]) );
}
}

} else {
System.out.println("Error");
}

我做错了什么?

最佳答案

不是c#吗?我不确定我是否理解你的意思。

在 C# 中,你尝试过类似的事情吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args) {

// Scanner in = new Scanner(System.in);
// String amount = Console.ReadLine();
String amount = "2*7*6*5*3*2";

if (amount.Contains('+')) {
String[] parts = amount.Split('+');

}
else
if (amount.Contains('-')) {
String[] parts = amount.Split('-');
}
else if (amount.Contains("*")) {
String[] parts = amount.Split('*');
int[] results = new int[parts.Length];

// Convert from string to integer
for (int i = 0; i < parts.Length; i++) {
try {
results[i] = int.Parse(parts[i]);
}
catch (FormatException nfe) { };
}

// Print result
int total = results[0];

for (int i = 1; i < results.Length; i++) {

if (i == 1)
Console.WriteLine(" " + results[i - 1]);

Console.WriteLine("* " + results[i]);
Console.WriteLine("----");

total = multiply(results[i], total);
Console.WriteLine(" " + total);
}

}
else {
Console.WriteLine("Error");
}

Console.ReadKey();
}

public static int add(int a, int b) {
return a + b;
}

public static int sub(int a, int b) {
return a - b;
}

public static int multiply(int a, int b) {
return a * b;
}

public static void main(String[] args) {


}
}

}

关于java - 计算器,无法按我想要的方式打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27982551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com