gpt4 book ai didi

java - 如何将我的程序分解为多个方法?

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

我如何将这个java程序分解为多个方法?它首先存储一个字符串作为输入,然后循环遍历它以将所有数字提取到数组列表中。然后它打印所有这些数字及其总和和乘积。

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

// Creates scanner for storing input string
Scanner numScanner = new Scanner(System.in);
String input;
System.out.println("Enter a string of numbers to compute their sum and product:");
System.out.println("(Enter '.' to terminate program)");
input = numScanner.nextLine();


// Terminates the program if there is no input
if (input.length() == 0){
System.out.println("Invalid input: Not enough characters");
System.exit(-1);
}


// Terminates the program if the first character is '.'
if (input.charAt(0) == '.'){
System.out.println("Thank you for using numberScanner!");
System.exit(-1);
}


// Defines all of the variables used in the loops
int index = 0;
int sum = 0;
int product = 1;
Integer start = null;
int end = 0;
ArrayList<Integer> numbers = new ArrayList<>();


// Loop that extracts all numbers from the string and computes their sum and product
while (index < input.length()){
if (input.charAt(index) >= 'A' && input.charAt(index) <= 'Z' && start == null){
index++;
}else if (input.charAt(index) >= '1' && input.charAt(index) <= '9' && start == null){
start = index;
index++;
}else if (Character.isDigit(input.charAt(index))){
index++;
}else{
end = index;
numbers.add(Integer.parseInt(input.substring(start,end)));
sum += Integer.parseInt(input.substring(start,end));
product *= Integer.parseInt(input.substring(start,end));
index++;
start = null;
}
}


// For the last number, the end is greater than the length of the string
// This prints the last number without using the end
if (index == input.length()){
numbers.add(Integer.parseInt(input.substring(start)));
sum += Integer.parseInt(input.substring(start));
product *= Integer.parseInt(input.substring(start));
index++;
}


// Prints the Numbers, Sum and Product beside each other
System.out.print("Numbers: ");
for (Object a : numbers) {
System.out.print(a.toString() + " ");
}
System.out.println("Sum: " + sum + " Product: " + product);
}

}

我只是不知道如何将单个方法拆分为多个方法

最佳答案

我认为在 main 方法中进行 I/O 就可以了。我要移出的是 numbers 列表的构造。您可以使用一个方法 getNumbers 来接受字符串并返回该字符串中的数字列表。例如:

private static List<Integer> getNumbers(String str) {
List<Integer> numbers = new ArrayList<>();

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);

if (Character.isDigit(c))
numbers.add(c - '0');
}

return numbers;
}

现在,循环遍历 getNumbers() 返回的列表并计算元素的和/积应该很简单:

List<Integer> numbers = getNumbers(input);

System.out.println(numbers);

int sum = 0;
int product = 1;

for (int i : numbers) {
sum += i;
product *= i;
}

System.out.printf("Sum: %d Product: %d%n", sum, product);

关于java - 如何将我的程序分解为多个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501454/

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