到目前为止我已经买了三本书并观看了几个视频,我仍然不清楚为什么这不能编译。任何帮助将不胜感激。我正在尝试读取信用卡号码文件,并检查用户输入的号码是否在我的主号码中。当我在main中调用isValid方法时,我非常确定我必须将数组作为参数,但是当我这样做时,我会得到'.class'。这是我的课程,然后是我的主要课程: (感谢您的帮助)
import java.util.Scanner;
import java.io.*;
public class Validator1
{
int[] valid;
public Validator1()throws IOException
{
}
public Validator1(String fileName)throws IOException
{
int beginning = 0;
int place = 0;
int size = 0;
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
Scanner inputFile2 = new Scanner(file);
while(inputFile.hasNextInt())
{
size++;
inputFile2.nextInt();
}
while(inputFile2.hasNextInt() && place < valid.length)
{
valid[place] = inputFile2.nextInt();
place++;
}
}
public void sort(int[]valid)
{
valid = new int[valid.length];
for(int start = 0; start < valid.length; start++)
{
int lowestValue = valid[start];
int lowestIndex = start;
for(int i = start + 1; i < valid.length; i++)
{
if(valid[i] < lowestValue)
{
lowestValue = valid[i];
lowestIndex = i;
}
}
int temp = valid[start];
valid[start] = valid[lowestIndex];
valid[lowestIndex] = temp;
}
}
public boolean isValid(int[] valid, int number)
{
int low =0;
int high = valid.length-1;
while(high >= low)
{
int middle = (high + low)/2;
if(valid[middle] == number)
{
return true;
}
if (valid[middle] < number)
{
low = middle +1;
}
if(valid[middle] > number)
{
high = middle-1;
}
}
return false;
}
}
import java.util.Scanner;
import java.io.*;
public class ChargeIt1
{
public static void main(String[] args)
{
int accountNumber;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileName1 = keyboard.nextLine();
String fileName = fileName1 + ".txt";
File file = new File(fileName);
while(!file.exists())
{
System.out.println("the file does not exist");
System.out.println("Enter the file name: ");
fileName1 = keyboard.nextLine();
fileName = fileName1 + ".txt";
file = new File(fileName);
}
System.out.println("Enter your charge account number: ");
accountNumber = keyboard.nextInt();
//Validator1 val = new Validator1(fileName);
try
{
Validator1 val = new Validator1(fileName);
if(val.isValid(valid[], accountNumber))
System.out.println("That is a valid account number.");
else
System.out.println("That is an INVALID account number.");
}
catch(Exception e)
{
//System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
这一行错了:
int[] valid = 0;
0不是数组。
答案 1 :(得分:1)
您的问题出在ChargeIt1
课程中,此处:
if(val.isValid(valid[], accountNumber))
System.out.println("That is a valid account number.");
else
System.out.println("That is an INVALID account number.");
val.idValid
方法(valid[]
)的第一个参数是非法语法。用这个替换该行:
if(val.isValid(valid, accountNumber))
这应该照顾你的编译器错误。请注意,这是一个可以通过IDE快速突出显示的内容,我强烈建议在开始编程时使用 特别是 。
答案 2 :(得分:0)
您的代码中有很多错误。
要解决这一问题:
int[] valid = 0; // does not compile
您有几个选项可以解决它:
数组的长度是固定的,要初始化数组,您必须提供维度,例如:
int[] valid = new int[10];
但是,由于数组是固定的,因此您的代码可以读取比数组有空间的更多输入。还有另一种方法 - 使用Collections,根据需要自动扩展尺寸。