第一题:输入二元数组不定大小,输出没有重合的区域
输入:
1 3
10 16
2 6
9 11
输出:
1 6
9 16
这道题感觉挺简单的,但是最后我纠结了一个多小时都没有完成输入的部分。后面看到有人用定时器的方式判断了结束,感觉这个应该不错。
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Test01 {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(sb);
}
},2000);
while (sc.hasNextLine()){
sb.append(sc.nextLine());
}
}
}
以上代码通过使用定时器完成数据的获取,但是hasNextLine还是会阻塞等待。
第二题:计算8+3*2-6/2+12的结果
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
Deque<Integer> num = new LinkedList<Integer>();
Deque<String> operator = new LinkedList<String>();
int pre=0,index;
while (pre<s.length()){
index=0;
if(s.charAt(pre)=='-'||s.charAt(pre)=='+'){
operator.push(s.substring(pre,pre+1));
pre++;
continue;
}
if(s.charAt(pre)=='*'){
int op = 1;
while(pre+op<s.length()&&(s.charAt(pre+op)!='-'&&s.charAt(pre+op)!='+'&&s.charAt(pre+op)!='*'&&s.charAt(pre+op)!='/')){
op++;
}
int temp = num.pop()*Integer.valueOf(s.substring(pre+1,pre+op));
pre=op+pre;
num.push(temp);
continue;
}
if(s.charAt(pre)=='/'){
int op = 1;
while(pre+op<s.length()&&(s.charAt(pre+op)!='-'&&s.charAt(pre+op)!='+'&&s.charAt(pre+op)!='*'&&s.charAt(pre+op)!='/')){
op++;
}
int temp = num.pop()/Integer.valueOf(s.substring(pre+1,pre+op));
num.push(temp);
pre=op+pre;
continue;
}
while(pre+index<s.length()&&(s.charAt(pre+index)!='-'&&s.charAt(pre+index)!='+'&&s.charAt(pre+index)!='*'&&s.charAt(pre+index)!='/')){
index++;
}
num.push(Integer.valueOf(s.substring(pre,pre+index)));
pre=index+pre;
}
while (!num.isEmpty()&&!operator.isEmpty()){
int temp = operatorMethon(num.removeLast(),num.removeLast(),operator.removeLast());
num.add(temp);
}
System.out.println(num.removeFirst());
}
public static int operatorMethon(int a,int b,String op){
char c = op.charAt(0);
if(c=='+'){
return a+b;
}else
return a-b;
}
}
以上代码都是考试完之后自己再写的,代码有点乱没有进行整理和优化,只是完成了大概的功能,边界值都没有做判断。