java - 如何生成整数数字的平方
问题描述
我正在尝试编写一个接受输入的命令行程序。如果输入是整数,它会将数字的每个数字平方并将它们连接起来,但如果输入不是整数,那么它会要求用户输入一个数字。但是输出是错误的。请检查代码。
package com.company;
import java.util.*;
public class ExerciseB {
public static void main (String[] args) {
while (true) {
System.out.println("Enter a digit or 'quit' to quit: ");
Scanner userInput = new Scanner(System.in);
if (userInput.hasNextInt()) {
int intInput = userInput.nextInt();
int i;
int intCharSquare;
ArrayList<Integer> valueCharSquare = new ArrayList<>();
//Generating the square of each character of the inputted integer and adding it to the valueCharSquare ArrayList
String stringOfIntInput= String.valueOf(intInput);
for (i = 0; i <= stringOfIntInput.length() - 1; i++) {
intCharSquare = (int) Math.pow((int) stringOfIntInput.charAt(i),2);
valueCharSquare.add(intCharSquare);
}
// Storing the first value of the valueCharSquare ArrayList into a variable
int result = valueCharSquare.get(0);
//Converting the value of result into a string
String.valueOf(result);
/* Obtaining the other values of the valueCharSquare ArrayList
* and storing them into otherResult variable
* then converting otherResult into a string
* then concatenating the values of result and otherResults
*/
for (i = 1; i <= valueCharSquare.size() - 1; i++) {
int otherResults = valueCharSquare.get(i);
String.valueOf(otherResults);
result = result + otherResults;
}
//printing out new value of result
System.out.println(result);
// This happens if the user input is a string
} else if (userInput.hasNext()) {
String stringInput = userInput.nextLine();
if (stringInput.equals("quit")) {
break;
} else {
continue;
}
}
}
}
}
解决方案
您应该编写一个单独的方法来对整数的数字进行平方,例如:
static String squareDigits(int number) {
String numberString = Integer.toString(number);
StringBuilder buf = new StringBuilder();
if (number < 0)
buf.append('-');
for (int i = (number < 0 ? 1 : 0); i < numberString.length(); i++) {
int digit = Character.digit(numberString.charAt(i), 10);
buf.append(digit * digit);
}
return buf.toString();
}
然后,您可以独立于用户输入/输出逻辑对其进行测试:
System.out.println(squareDigits(13579)); // prints: 19254981
System.out.println(squareDigits(-2468)); // prints: -4163664
System.out.println(squareDigits(0)); // prints: 0
System.out.println(squareDigits(1999999999)); // prints: 1818181818181818181
推荐阅读
- c# - 如何使用 EF Core MongoDB 驱动程序比较表达式中的字符串和日期时间?
- javascript - 找不到容器dom元素融合图
- spring-boot - 对于未经身份验证的请求,Keyclock springboot 返回 403 而不是 401
- node.js - 为什么有些 URL 后面没有“follow-redirects”npm 包?
- cucumber - JIRA 的 XRAY “错误”:“customfield_11714:customfield_11714”
- javascript - 我如何在本机反应中多次使用组件
- android - 在 LazyColumn 中是否有任何正确(有效)的方式来使用 CustomView(有或没有 androidx.compose.ui.viewinterop.AndroidView)?
- c++ - Eclipse 调试 C++ 在 MacOS 上不起作用
- python - Сreating一个python字典从几个
- database - 拆分 REST API 和消息代理使用者