Input to array stopped by "quit " word - java

I need to do Football Results Generator. I created 4 arrays with 10 elements each, but I need to include a loop that allows the user to change their mind and stop input by typing "quit" after a certain number of entries. Could you please help - I am new to programming, so it must be dead simple.
import java.util.Scanner;//
public class Football_Results_Generator
{
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
String[] HomeTeam = new String[10];
String[] AwayTeam = new String[10];
int[] HomeScore = new int[10];
int[] AwayScore = new int[10];
int index = 0;
int sum = 0;
int sum1 = 0;
do
{
System.out.print("Enter Home Team Name: ");
HomeTeam[index] = kbd.nextLine();
System.out.print("Enter Away Team Name: ");
AwayTeam[index] = kbd.nextLine();
System.out.print("Enter Home Team Score:");
HomeScore[index] = kbd.nextInt();
System.out.print("Enter Away Team Score: ");
AwayScore[index] = kbd.nextInt();
kbd.nextLine();
} while(index < 10);
index = 0;
System.out.println();
do
{
System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
index = index + 1;
} while(index < 10);
kbd.close();
for(index = 0; index < 10; index++)
sum += HomeScore[index];
for(index = 0; index < 10; index++)
sum1 += AwayScore[index];
System.out.println();
System.out.println("Totals");
System.out.println("-------------------------------");
System.out.println("Total number of matches played: " + index);
System.out.println("Total of all home scores: " + sum);
System.out.println("Total of all away scores: " + sum1);
System.out.println("Total number of draws: ");
System.out.println("The highest home score: ");
System.out.println("The highest away score: ");
}
}

allow user to change his mind and stop input by typing quit after 5 tries.
Use a temp variable to capture String input:
String line;
do
{
System.out.print("Enter Home Team Name: ");
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
HomeTeam[index] = line;
.....
index = index + 1; //missed
}while(index < 10);
index = 0;
Here, "quit".equalsIgnoreCase(line) will ensure that irrespctive of case of line e.g. "Quit","QUIT","quit",etc will result true
What about integer input to array?? is it same concept ??
Well, you need to handle the exception in case input is neither quit nor int:
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
try{
HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
//Error conversion string to int
}

Related

Index match max/min scores (Java)

I am working through a coding assignment and am close to completion save for my final print statement which needs to match names w/ scores for max and min.
I have been able to get appropriate values in two sentences using two if statements, but I am a bit stumped on how to get my indexing correct to align names to scores w/ max and min.
I am not able to use classes or additional / different methods other than arrays and indexing.
//Create method StudentMax
private static int StudentMax(int[] Scores) {
int ScoreMax = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] > ScoreMax){
ScoreMax = Scores[i];
}
}
return ScoreMax;
}
//Create method StudentMin
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
}
}
return ScoreMin;
}
public static void main(String[] args) {
//Call Scanner
Scanner scan = new Scanner(System.in);
//User Welcome
System.out.println("Welcome to the student score sorter.");
System.out.println("\nThis program will accept a number of student names and score values, then find the highest and lowest score.");
System.out.println("\nThen will return the names and max/min scores.");
//User Prompt Enter number of students
System.out.println("\nHow many students would you like to enter: ");
int StudentCount = scan.nextInt();
//Create arrays: Scores, StudentFirst, StudentLast
int [] Scores = new int[StudentCount];
String [] StudentFirst = new String [StudentCount];
String [] StudentLast = new String [StudentCount];
for (int i = 0; i < Scores.length; i++) {
System.out.println("\nStudent " + (i+1)+":");
System.out.println("\nEnter Student's name:");
StudentFirst[i] = scan.next();
StudentLast[i] = scan.next();
System.out.println("\nEnter Student's score (0-100):");
Scores[i] = scan.nextInt();
}
int max = StudentMax(Scores);
int min = StudentMin(Scores);
for (int i = 0; i < Scores.length; i++) {
System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +": " + Scores[i]);
}
for (int i = 0; i < Scores.length; i++) {
if (Scores [i] == max) {
System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
}
}
//This is the sentence format that I need to make work, but I am struggling to understand how to align the index for names and scores.
//System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);
//Scan Close
scan.close();
//Close Program
}
}
Pass back the index not the value
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
int index = 0;
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
index = i;
}
}
return index;
}
Then you can use it later
int index = StudentMax(Scores);
System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);
Note Please pay attention to Java naming conventions

How to loop a user input until integer is entered?

I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}

Jcreator Voting Program

My teacher wants us to make a program that counts the total number of votes for two candidates from a variable number of precincts. So the user inputs the candidates’ names as strings and is then prompted to enter the number of precincts prior to entering the votes for each precinct. What I am having trouble with is that I have to use an array to keep each precinct's vote total. Then after all of that is done I have to keep a running total of the votes for each candidate after each precinct is completed and who is currently leading and by how much. I have already begun my program but I am honestly just lost as to where to go from here, and I know that what I have in my arrays so far is not correct.
import java.util.*;
public class Voting
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int rerun;
int rerun2;
while (rerun == 1)
{
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
presincts = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 1: ");
votes1 = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 2: ");
votes2 = scan.nextInt();
while (rerun2 == 1 && precincts >= 0 && votes1 >= 0 && votes2 >= 0)
{
int[] votes1 = new int[precincts];
for(int i = 0; i < votes1.length; i++)
{
votes1[i] = int [i];
System.out.println ("\n" + votes1);
}
int[] votes2 = new int[precincts];
for(int i = 0; i < votes2.length; i++)
{
votes2[i] = int [i];
System.out.println ("\n" + votes2);
}
}
}
}
}
I don't know what the function of rerun is so I've left it out of this answer.
First thing you're going to want to do is initialize your variables at the start of your class:
String candidate1;
String candidate2;
int precincts;
int vote1;
int vote2;
int total1;
int total2;
int[] votes1;
int[] votes2;
Note you had a typo in precincts
Then you need to get the name of the candidates and the number of precincts (you've done this correctly already):
Scanner scan = new Scanner(System.in);
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
precincts = scan.nextInt();
Then you need to iterate through the number of precincts, and get the number of votes for each candidate from each precinct. You can do this by initializing an empty array which will keep the votes stored (eg, the votes for the first candidate in precinct 1 will be stored in votes1[0]). Additionally, the easiest way to keep a running total is to use a separate variable total1 and total2:
total1 = 0;
total2 = 0;
votes1 = new int[precincts];
votes2 = new int[precincts];
for (int i = 0; i < precincts; i++) {
System.out.print("\nPlease enter amount of votes for candidate 1 in precinct " + (i + 1) + ": ");
vote1 = scan.nextInt();
votes1[i] = vote1;
total1 = total1 + vote1;
System.out.print("\nPlease enter amount of votes for candidate 2 in precinct " + (i + 1) + ": ");
vote2 = scan.nextInt();
votes2[i] = vote2;
total2 = total2 + vote2;
}
From inside the for loop you can do things like print the current total votes for a candidate:
System.out.println(candidate1 + " has " + total1 + " votes in total");
And print out who is the current leader and by how many votes:
if (total1 > total2) {
System.out.println(candidate1 + " is winning by " + (total1-total2) + " votes");
} else {
System.out.println(candidate2 + " is winning by " + (total2-total1) + " votes");
}

sorting, average and finding the lowest number from a static array Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i'm trying to input students and input their results for course work and exams and what i'm having trouble with is finding the average total score, the lowest total score and printing all students in order of total scores highest - lowest
import java.util.*;
import java.text.*;
public class Results
{
static String[] name = new String[100];
static int[] coursework = new int[100];
static int[] exam = new int[100];
static int[] totalScore = new int[100];
static String[] totalGrade = new String[100];
static String[]examGrade = new String[100];
static int count = 0;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean flag = true;
while(flag)
{
System.out.println(
"1. Add Student\n" +
"2. List All Students\n" +
"3. List Student Grades\n" +
"4. Total Score Average\n" +
"5. Highest Total Score\n" +
"6. Lowest Total Score\n" +
"7. List all Students and Total Scores\n" +
"8. Quit\n");
System.out.print("Enter choice (1 - 8): ");
int choice = input.nextInt();
switch(choice)
{
case 1:
add();
break;
case 2:
listAll();
break;
case 3:
listGrades();
break;
case 4:
average();
break;
case 5:
highestTotal();
break;
case 6:
lowestTotal();
break;
case 7:
order();
break;
case 8:
flag = false;
break;
default:
System.out.println("\nNot an option\n");
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
System.out.println("\n\nHave a nice day");
}//end of main
static void add()
{
Scanner input = new Scanner(System.in);
System.out.println("Insert Name: ");
String names = input.nextLine();
System.out.println("Insert Coursework: ");
int courseworks = input.nextInt();
System.out.println("Insert Exam: ");
int exams = input.nextInt();
int totalscores = exams + courseworks;
name[count] = names;
coursework[count] = courseworks;
exam[count] = exams;
totalScore[count] = totalscores;
count++;
}
static void listAll()
{
for(int i=0;i<count;i++)
{
System.out.printf("%s %d %d\n", name[i], coursework[i], exam[i]);
}
}
static void listGrades()
{
for(int i=0;i<count;i++){
if(coursework[i] + exam[i] > 79)
{
System.out.println(name[i] + " HD");
}
else if(coursework[i] + exam[i] > 69)
{
System.out.println(name[i] + " DI");
}
else if(coursework[i] + exam[i] > 59)
{
System.out.println(name[i] + " CR");
}
else if(coursework[i] + exam[i] > 49)
{
System.out.println(name[i] + " PA");
}
else
{
System.out.println(name[i] + " NN");
}
}
}
static void average()
{
double sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score : %.1f\n ", sum);
}
static void highestTotal()
{
int largest = totalScore[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (totalScore[i] > largest) {
largest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
static void lowestTotal()
{
int lowest = totalScore[0];
String student = name[0];
for (int i = 0; i > exam.length; i++) {
if (totalScore[i] < lowest) {
lowest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + lowest + "\n");
}
static void order()
{
for (int i=0;i<count;i++)
{
Arrays.sort(totalScore);
System.out.printf(name[i] + "\t" + totalScore[count] + "\n");
}
}
}
static void average(){
int total = 0;
for(int i = 0; i < array.length; i++)
{
total += array[i];
}
int average = total / array.length
}
Above code you can get the Average. You did the kind of similar thing to find largest value.
to sort array just use that will solve your problem.
Arrays.sort(array);
For sorting, you can use Arrays.sort(array) (With a comparator if you need special ordering)
Once it's sorted, getting the lowest score should be easy. To get an average, add up each value and divide by the number of elements. To add them all up, use a for loop or for-each loop:
int sum = 0;
for(int i = 0; i < array.length; i++)
{
sum += array[i];
}
int average = sum / array.length
You may want to use a double instead of an int for sum.
For Average Total Score simply add the coursework and exam scores in avariable such as sum and divide by no. of students:
static void average() {
int sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score = : " + sum + "\n");
}
For both lowest total score and largest total score your implementation of highest total is almost right. The problem is that you are not considering the coursework[i] in your largest variable. And on similar lines you can implement lowest total score
static void highestTotal() {
int largest = exam[0] + coursework[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (exam[i]+coursework[i] > largest) {
largest = exam[i] + coursework[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
For printing the scores in order i would suggest that you define another int array which has the sum of exam score and coursework score, sort it using any basic sorting technique and print the array. Remember while exchanging the sum during sorting also exchange the corresponding name..

Java entering test score validation

I am trying to output the amount of test scores between 5 and 35. I do get an invalid entry when the integer entered is below 5 or above 35, which is required. However, when I enter a number between 5 and 35, nothing happens. I get a blank line. The only way I can get "Enter Score" to show up is when I enter another number and press "Enter/Return". What am I doing wrong?
Here is my code:
============================
import java.text.NumberFormat;
import java.util.Scanner;
public class ValidatedTestScoreApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int maximumScore = 0;
int minimumScore = 100;
// get the number of scores to be entered
int amtTest = getIntWithinRange(sc,"Enter the number of test scores to be entered: ", 5, 35);
int numberOfEntries = sc.nextInt();
System.out.println();
sc.nextLine();
for (int i = 1; i <= numberOfEntries; i++)
{
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
maximumScore = Math.max(maximumScore, testScore);
minimumScore = Math.min(minimumScore, testScore);
}
else if (testScore != 999)
{
System.out.println("Invalid entry, not counted");
i--;
}
}
// calculate the average score
double averageScore = (double) scoreTotal / (double) scoreCount;
// display the results
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + number.format(averageScore) + "\n"
+ "Minimum score: " + minimumScore + "\n"
+ "Maximum score: " + maximumScore + "\n";
System.out.println(message);
// see if the user wants to enter more test scores
System.out.print("Enter more test scores? (y/n): ");
choice = sc.next();
System.out.println();
}
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
}
The problem is that you are trying to read the values multiple times.
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
Here you already got the value from the getIntWithinRangeMethod, but on the next line you are reading it again.
Also what are the amtTest and testScores variables good for? I'm not sure what you are trying to accomplish, but I guess you need to do these two changes:
// get the number of scores to be entered
// int amtTest = getIntWithinRange(sc, "Enter the number of test scores to be entered: ", 5, 35);
// int numberOfEntries = sc.nextInt();
int numberOfEntries = getInt(sc, "Enter the number of test scores to be entered: ");
// System.out.println();
// sc.nextLine();
...
// int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
After this, the programs behaves fine and I get this:
Enter the number of test scores to be entered: 2
Enter score 1: 5
Enter score 2: 6
Score count: 2
Score total: 11
Average score: 5.5
Minimum score: 5
Maximum score: 6
Enter more test scores? (y/n):

Categories