目前我收到java.lang.NumberFormatException:错误。我无法修复它。
这是我目前的代码:
import java.util.*;
import java.lang.*;
/**
* Write a description of class Square here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Square {
public static void main(String[] args) {
Scanner firstInput = new Scanner(System.in);
Scanner secondInput = new Scanner(System.in);
String n = firstInput.next();
n = n.replaceAll("[*0-9]","");
int b = Integer.parseInt(n);
int[] squares = new int[b];
int[] squared = new int[b];
for(int i = 0; i <= squares.length - 1; i++ ) {
System.out.print("Write square number " + (i + 1) + " : " );
squares[i] = secondInput.nextInt();
}
for(int j = 0; j <= squares.length - 1; j++) {
squared[j] = squares[j] * squares[j];
}
System.out.print("The square of inputted numbers are: ");
for(int k = 0; k <= squared.length - 1; k++) {
System.out.print(squared[k] + " ");
}
}
}
这是我得到的错误:
java.lang.NumberFormatException: For input string: "java"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Square.main(Square.java:17)
基本上,用户输入将是&#34; java square 5&#34;例如,并且它将检测值5,将数组的大小设置为5,然后它向该人询问他/她想要平方的5个数字。
当只有整数时,上述规定有效,但是当我放入一个字符串时,它就会停止工作。
任何帮助将不胜感激!
注意:我知道我的代码可能很糟糕,我还在学习!
答案 0 :(得分:0)
您应该只有一台扫描仪。两个扫描仪相互竞争以从System.in读取。然后你需要扫描两次以获得令牌“java”和“square”。然后你可以开始循环来获取.nextInt()s。
Scanner input = new Scanner(System.in);
input.next(); // should be "java"
input.next(); // should be "square"
input.nextInt(); // should be 5