Java 方法不起作用?
更新代码:Java 方法不起作用?,java,Java,更新代码: import java.util.*; public class Main { /** * @param args */ static int[] C; static int[] D; static String P; public static void main(String[] args) { C = new int[10]; D = new int[10]; getNumber(); } private static void getNum
import java.util.*;
public class Main {
/**
* @param args
*/
static int[] C;
static int[] D;
static String P;
public static void main(String[] args) {
C = new int[10];
D = new int[10];
getNumber();
}
private static void getNumber() {
System.out
.println("Enter your first number with spaces in between digits.");
Scanner S = new Scanner(System.in);
String O = S.nextLine();
String[] A = new String[10];
A = O.split(" ");
for (int X = 0; A.length > X; X++) {
C[X] = toNumber(A[X]);
}
String P = S.nextLine();
String[] B = new String[10];
B = P.split(" ");
for (int Y = 0; B.length > Y; Y++) {
C[Y] = toNumber(A[Y]);
}
System.out.print(C[0]);
remainders();
}
private static void remainders() {
for (int A = 0; C.length > A; A++) {
if (D[1] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
for (int A = 0; C.length > A; A++) {
if (D[0] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
System.out.print(P);
}
private static int toNumber(String string) {
if (string.equals("0")) {
return 0;
} else if (string.equals("1")) {
return 1;
} else if (string.equals("2")) {
return 2;
} else if (string.equals("3")) {
return 3;
} else if (string.equals("4")) {
return 4;
} else if (string.equals("5")) {
return 5;
} else if (string.equals("6")) {
return 6;
} else if (string.equals("7")) {
return 7;
} else if (string.equals("8")) {
return 8;
} else if (string.equals("9")) {
return 9;
} else {
return 0;
}
}
}
出于某种原因,它最后打印的内容是null
。我很确定问题出在toNumber
方法上,但我不知道出了什么问题。如果代码有其他问题,请告诉我。请帮忙。
编辑:问题似乎出在余数方法上,请帮助使用
字符串.equals(n)
方法测试字符串是否为n
字符串常量的比较方式为:“0”。equals(string)
。字符串文字是实际的String
对象,您可以对它们调用任何字符串方法。您应该更喜欢对常量调用方法,因为可以保证它们存在,而变量可以是null
。
你不需要重新发明轮子。Java有丰富的SDK。
简单使用
int x = Integer.valueOf(a[X]);
如果您只需要数字0-9,那么只需进行测试
if (0 <= x && x <= 9) {
//valid continue
} else {
//invalid state handling
}
if(0)首先,您需要使用equals()
方法类似于这样的if(string.equals(“0”)
第二件事,您的方法名没有遵循Java命名约定。您的方法GetNumber()
应该看起来像GetNumber()
和Remainders()
likeremainders()
这是家庭作业吗?如果是,请这样标记。请为您的问题选择一个更具描述性的标题…已修复该问题,但问题似乎在于剩余方法