package com.itheima;
import java.io.*;
import java.util.Scanner;
import static java.lang.System.exit;
public class Main{
static String bt = "D:\\chapter07\\bbq";
static Scanner in = new Scanner(System.in);
public static void main(String[] args)throws Exception{
while(true) {
menu();
operate();
}
}
public static void menu(){
System.out.println("----------------微信投票---------------");
System.out.println("(1)添加候选人 (2)查看当前投票");
System.out.println("(3)投票 (4)退出 ");
}
public static void operate()throws Exception{
System.out.print("请输入需要进行的操作:");
int d = in.nextInt();
switch(d)
{
case 1: add();break;
case 2: look();break;
case 3: vote(); break;
case 4: exit(0);
default: System.out.println("输入范围错误,请重新输入");
}
}
//添加
public static void add()throws IOException {
String people;
System.out.print("请输入候选人:");
people = in.next();
people += ".txt";
File file = new File(bt, people);
if(file.exists())
{
System.out.println("该候选人已存在");
}
else
{
if(file.createNewFile())
System.out.println("添加成功");
else
System.out.println("添加失败");
FileWriter writer = new FileWriter(file);
writer.write("0");
writer.close();
}
}
//查看
public static void look()throws Exception{
File file = new File(bt);
String[] names = file.list();
boolean flag = false;
for (String name : names) {
flag = true;
System.out.println("候选人:" + removeExtension(name));
System.out.print("拥有的票数为:");
String str = bt + "\\" + name;
FileReader reader = new FileReader(str);
int ch;
while ((ch = reader.read()) != -1)
System.out.println(ch - '0');
reader.close();
}
if(!flag)
{
System.out.println("不存在候选人,请先添加候选人");
}
}
public static String removeExtension(String fname){
int pos = fname.lastIndexOf('.');
if(pos > -1)
return fname.substring(0, pos);
else
return fname;
}
//投票
public static void vote()throws IOException{
System.out.print("请输入候选人:");
String candidate;
candidate = in.next();
candidate += ".txt";
File file = new File(bt);
String[] names = file.list();
boolean flag = false;
for(String name : names)
{
if(name.equals(candidate))
{
flag = true;
break;
}
}
if(flag)
{
String str = bt + "\\" + candidate;
FileReader reader = new FileReader(str);
int ch;
String d = "";
while((ch = reader.read()) != -1)
d = String.valueOf(ch - 47);
FileWriter writer = new FileWriter(str);
writer.write(d);
System.out.println("投票成功");
reader.close();
writer.close();
}
else{
System.out.println("不存在该候选人");
}
}
}
java基础案例7-5微信投票
最新推荐文章于 2024-07-26 12:28:02 发布