JAVA oj注意事项

来源:互联网 发布:为什么卸载不了软件 编辑:程序博客网 时间:2024/06/06 08:39
基本输入输出
其实我感觉在有c基础后,学习java还是挺简单的,写acm时候主要是不太适应java的输入输出,其实关键还是在于你心里是否接受java的语法(吐槽:java的api的名字太TM长了吧)
 
在c里输入输出的标准格式:
 
[cpp]  
#include <stdio.h>  
  
int main(void)  
{  
    int a, b;  
  
    while (scanf("%d %d", &a, &b) != EOF) {  
        printf("%d\n", a + b);  
    }  
  
    return 0;  
}  
 
 
在java里提供了Scanner类可以方便我们跟c一样进行输入输出:
 
[java]  
import java.util.*;  
  
  
public class IOclass {  
    public static void main(String[] args) {  
        Scanner cin = new Scanner(System.in);  
          
        int a, b;  
          
        while (cin.hasNext()) {  
            a = cin.nextInt();  
            b = cin.nextInt();  
              
            System.out.printf("%d\n", a + b);  
        }  
    }  
}  
 
 
API对比(java vs c):
 
读一个整数  int a = cin.nextInt(); 相当于 scanf("%d", &a);
 
读一个字符串 String s = cin.next(); 相当于 scanf("%s", s);
 
读一个浮点数 double t = cin.nextDouble(); 相当于 scanf("%lf", t);
 
读取整行数据 String s = cin.nextLine() 相当于 gets(s);
 
判断是否有下一个输出 while (cin.hasNext) 相当于 while (scanf("%d", &n) != EOF)
 
输出 System.out.printf(); 相当于 printf();
 
 
方法调用
在java主类中main方法必须是public static void的,在main中调用非static方法时会报出错误,因此需要先建立对象,然后调用对象的方法
 
题目
[html]  
Given an array of integers, every element appears twice except for one. Find that single one.  
  
Note:  
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?  
 
代码
[java] 
import java.util.*;  
  
public class SingleNumber {  
    public static void main(String[] args) {  
        int n, key, A[] = new int[1000];  
          
        Scanner cin = new Scanner(System.in);  
          
        while (cin.hasNext()) {  
            // 接收数组A  
            n = cin.nextInt();  
            for (int i = 0; i < n; i ++) {  
                A[i] = cin.nextInt();  
            }  
              
            // 调用方法  
            SingleNumber sn = new SingleNumber();  
  
            key = sn.singleNumber(A, n);  
  
            System.out.println(key);  
              
        }  
    }  
  
    public int singleNumber(int[] A,  int n) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
  
        for (int i = 1; i < A.length; i++) {  
            A[0] ^= A[i];  
        }  
  
        return A[0];  
    }  
}  
 
0 0
原创粉丝点击