Finished Assignment 10

This commit is contained in:
Siwat Sirichai 2020-11-03 14:41:23 +07:00
parent c88ac94cc1
commit 48d8a7bf72
4 changed files with 89 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,43 @@
import java.util.*;
public class SchoolLottery{
private ArrayList<String> entries; // holds Student references
public SchoolLottery(){
entries = new ArrayList<>();
}
public void addStudents(){
// prompts for student names
// adds students to entries list
// allow duplicate entries
Scanner input = new Scanner(System.in);
int studentNum = 0;
System.out.println("Please Enter to end input");
System.out.print("Name" + ++studentNum + ": ");
String name = input.nextLine();
while (!name.equals("")){ // signals end of data
entries.add(name);
System.out.println(name + " entered in the lottery.");
System.out.print("\nName" + ++studentNum + ": ");
name = input.nextLine();
}
pickWinner();
}
public void pickWinner(){
// chooses a random entry and displays winners name
int numEntries = entries.size(); // size of ArrayList
if(numEntries == 0)
System.out.println("*** No participants ***");
else{
Random random = new Random();
String winner = entries.get(random.nextInt(numEntries));
System.out.print("\n*** The winner is " + winner + " ***");
}
}
public static void main(String[] args){
SchoolLottery lottery = new SchoolLottery();
lottery.addStudents();
}
}

View File

@ -0,0 +1,46 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class SchoolLotteryFromFile{
private ArrayList<String> entries; // holds Student references
public SchoolLotteryFromFile(){
entries = new ArrayList<>();
}
public void addStudents(String name){
if(entries.contains(name)) {
System.out.println("Duplicate Detected!, You think you're so smart? "+name);
return;
}
System.out.println(name + " entered in the lottery.");
entries.add(name);
}
public void pickWinner(){
// chooses a random entry and displays winners name
int numEntries = entries.size(); // size of ArrayList
if(numEntries == 0)
System.out.println("*** No participants ***");
else{
Random random = new Random();
String winner = entries.get(random.nextInt(numEntries));
System.out.print("\n*** The winner is " + winner + " ***");
}
}
public static void main(String[] args){
SchoolLotteryFromFile lottery = new SchoolLotteryFromFile();
Scanner sc;
try {
sc = new Scanner(new File("studentList.txt"));
while(sc.hasNextLine())lottery.addStudents(sc.nextLine());
lottery.pickWinner();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}