这是我写的,和你比起来怎样?{:soso_e120:}
我开始没看你的思路,昨天晚上就把题目记下来了,上班有时间想想思路,回来调试了下,共勉
public class BuyDrink {
public static void main(String[] args) throws IOException {
int person = 0;
person = readKey();
// System.out.println(person);
buyDrink(person);
}
public static void buyDrink(int person) {
int temp = 0, buy = 0, free = 0;
if (person <= 3)
System.out.println("人数较少,您需要购买" + person + "瓶汽水.");
else {
for (buy = 3, temp = 3; (buy + free) < person; ) {
if (temp == 3) {
free++;
temp = 1;
}
if ((buy + free) < person) {
buy++;
temp++;
}
}
System.out.println("您需要购买" + buy + "瓶汽水,免费送您" + free + "瓶汽水,"+"还有"+temp+"个
盖子");
}
public static int readKey() throws IOException {
System.out.println("请输入人数:");
int ch;
StringBuilder sb = new StringBuilder();
BufferedInputStream is = new BufferedInputStream(System.in);
while ((ch = is.read()) != -1) {
if (ch == '\r')
continue;
if (ch == '\n')
return Integer.parseInt(sb.toString());
if (Character.isDigit((char) ch))
sb.append((char) ch);
}
return Integer.parseInt(sb.toString());
}
} |