[英]Why is it printing null?
我只想打印用户在方法中输入的字符串“代码”,但它正在打印“null”,但是当我想打印 int num 时,它会打印用户输入的内容。 output 应打印用户输入的所有详细信息; 有点像身份证。 这应该很简单,但由于某种原因我无法做到,我开始失去希望。 任何帮助,将不胜感激。 谢谢
public class Lab2 {
static String code;
static String num;
int year;
static int sem;
public static void main(String[] args) {
info();
num();
sem();
System.out.println(num + " " + sem + " " + code);
}
public static void info() {
Scanner sc = new Scanner(System.in);
System.out.println("Course ID Generator\n--------------------------");
System.out.println("Please Enter Course Information:");
String message = "Initial";
String code = "";
while (!message.isEmpty()) {
if (!message.equals("Initial")) {
System.out.println(message);
}
System.out.print("Course Code (only capital letters " + "with a length between 2 and 4): ");
code = sc.nextLine();
message = checkLength(code);
if (message.isEmpty()) {
message = checkUpperCase(code);
}
}
}
private static String checkLength(String code) {
String output = "";
if (code.length() < 2 || code.length() > 4) {
output = "Course Code length was not between " + "2 and 4, Please try again";
}
return output;
}
private static String checkUpperCase(String code) {
String output = "";
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) && Character.isUpperCase(ch)) {
} else {
output = "Course Code must only have capital " + "letters, please try again";
break;
}
}
return output;
}
public static void num() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Course Number (consists of only 3 digits): ");
num = sc.nextLine();
if (num.length() == 3) {
break;
} else {
System.out.println("Course Number length was not 3, please try again");
}
sc.close();
}
}
public static void sem() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Semester (Fall=01, Sprint=02, Summer=03):");
sem = sc.nextInt();
if (sem > 0 && sem < 4) {
break;
} else {
System.out.println("Please enter correct semester code, try again");
}
}
sc.close();
}
}
删除线
String code = "";
在你的info
方法
您两次使用相同的变量code
。
阅读本文以获取更多信息https://dzone.com/articles/variable-shadowing-and-hiding-in-java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.