这适用于在线评委(Codeforces)。输入文件是这样的
input.txt中
6
4 3 2 1 5 6
第一行是数组大小,第二行包含数组元素。
我已经尝试过使用这个
了 public static int readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n = Sc.nextInt();
return n;
}
catch(Exception e){
return 0;
}
}
public static int[] readFiles(String file,int n){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
return null;
}
}
public static void main (String args [] ){
int n = readFiles("input.txt");
int arr [] = readFiles("input.txt",n);
答案 0 :(得分:1)
您可以调用构建数组的方法而不提供 let storyboard : UIStoryboard = UIStoryboard(name: "Messaging", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("PreferencesViewController") as! PreferencesViewController
vc.modalPresentationStyle = UIModalPresentationStyle.Popover
let popover: UIPopoverPresentationController = vc.popoverPresentationController!
vc.preferredContentSize = CGSize(width: 200, height: 200)
popover.barButtonItem = sender as? UIBarButtonItem
popover.delegate = self
presentViewController(vc, animated: true, completion:nil)
:
n
如果您需要public static void main (String args [] ){
int arr [] = readFiles("input.txt");
System.out.println(Arrays.toString(arr));
int n = arr.length;
System.out.println("n is: " + n);
}
public static int[] readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n= Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
System.out.println("The exception is: " + e);
e.printStackTrace();
return null;
}
}
,可以通过此行n
获取。
答案 1 :(得分:0)
你的代码永远不会工作,因为甚至没有编译
如果此方法readFiles(String file)
返回一个int,则执行此操作
int arr [] = readFiles("input.txt",n);
答案 2 :(得分:0)
为什么不在for循环中尝试这个以在空格之间拆分数字并将其存储在数组中:
int temp[] = Scanner.readLine().split(" ");
答案 3 :(得分:0)
你可以添加一个bufferedreader来一次读取一行,就像这样。
public static void main(String[] args) {
int[] numberArray = readFile();
}
public static int[] readFile(){
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
int arraySize = Integer.parseInt(br.readLine());
String[] arrayContent = br.readLine().split(" ");
int[] newArray = new int[arraySize];
for(int i = 0; i<arraySize; i++){
newArray[i] = Integer.parseInt(arrayContent[i]);
}
return newArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}