我试图从输入文件中读取整数" input.txt"并分隔整数并添加数字。我的这个代码给了我一个错误,说sum的方法是一个非法的开始。有什么指针吗?
public static void main(String[] args){
//declarations
boolean fileOpened = true;
Scanner inputFile = null;
int sumNum, num;
//read input
String fileName = " ";
System.out.println("Please input the name of the file to be opened: ");
Scanner input = new Scanner(System.in);
fileName = input.nextLine();
try{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){
System.out.println("--- File NOT Found! ---");
fileOpened = false;
}
if(fileOpened && inputFile.hasNext()){
sumNum = sum(num);//method call
while(inputFile.hasNextInt()){
if(inputFile.hasNextInt()){
num = inputFile.nextInt();
System.out.println("For number " + num + " the sum of the digits is: " + sumNum);
}
else{
inputFile.next();
}
}
}
public static int sum(int num){
int i, sumNum = 0;
for(i = 1; i <= num; i++){
sumNum += num % 10;
num /= 10;
}
return sumNum;
}
}
答案 0 :(得分:0)
您在主要方法中缺少}
。您还没有初始化num
。
我已修复主要输出正确的输出。你的方法还有其他问题。你在错误的地方调用sum
方法。请尝试以下答案:
public static void main(String[] args){
//declarations
boolean fileOpened = true;
Scanner inputFile = null;
int sumNum, num = 0;
//read input
String fileName = "";
System.out.println("Please input the name of the file to be opened: ");
Scanner input = new Scanner(System.in);
fileName = input.nextLine();
try{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){
System.out.println("--- File NOT Found! ---");
fileOpened = false;
}
while(inputFile.hasNextInt()){
num = inputFile.nextInt();
sumNum = sum(num);//method call
System.out.println("For number " + num + " the sum of the digits is: " + sumNum);
}
}