Ending a program with ctrl+Z - java

import java.util.Scanner;
public class ClassAverage
{
public static void main(String args[])
{
String names[] = new String[50];
int scores[] = new int[50];
int entries = 0;
Scanner in = new Scanner(System.in);
//System.out.println("Enter number of entries");
//int entry = in.nextInt();
System.out.println("Enter the names followed by scores of students: ");
for(int i = 0; i < 50; i++)
{
names[i] = in.next();
scores[i] = in.nextInt();
entries++;
}
Average avg = new Average();
double average = avg.CalcAvg(scores,entries);
System.out.println("The class average is: " + average);
avg.belowAvg(scores,average,names,entries);
avg.highestScore(scores,names, entries);
}
}
class Average
{
Average()
{
System.out.println("The averages: ");
}
double CalcAvg(int scores[], int entries)
{
double avg;
int total = 0;
for(int i = 0; i < entries; i++)
{
total += scores[i];
}
avg = total/entries;
return avg;
}
void belowAvg(int scores[],double average,String names[], int entries)
{
for(int i = 0; i < entries; i++)
{
if(scores[i] < average)
System.out.println(names[i] + "You're below class average");
}
}
void highestScore(int scores[],String names[], int entries)
{
int max = scores[1];
for(int i = 0; i < entries; i++)
{
if(scores[i]>=max)
max=scores[i];
}
System.out.println("The maximum score is: " + max);
System.out.println("The highest score acheivers list: ");
for(int i = 0; i < entries; i++)
{
if(scores[i] == max)
System.out.println(names[i]);
}
}
}
im suppose to hold the ctrlkey press z and then press the enter key to end the program but how do i do that?
if you are wondering the program is to write a program that lets the user input student names followed by their test scores and outputs the class average, names of students below the average, and the highest test score with the name of student

Ctrl-Z is the DOS command code for end of input (the UNIX equivalent is Ctrl-D). All command line programs should support this because it allows you to pipe output from one as input to the other. Kudos to your teacher!
When this key combo is pressed, Scanner.hasNextLine() will return false. Here's an example of a loop that reads line until you hit Ctrl-Z on Windows (or Ctrl-D on Linux/Unix):
while (in.hasNextLine()) {
System.out.println("You wrote " + in.nextLine());
}

You can listen for the control-z character in your scanner:
String nextLine = in.nextLine();
if(nextLine.length == 1 && nextLine.charAt(0) == KeyEvent.VK_Z)
// end program

Related

How to connect two class modules together in Java?

I have a program that contains five .txt files. These files are read in and put into different arrays. One is an array of names. The other four are arrays with test scores.
Currently, the program does create the arrays correctly. Next the program is to calculate and display the average for each test (this works fine). Then the program prompts the user for a name. If a name is found a new menu will prompt the user to select which test they want the data on. (This works fine).
The problem: I have the main program class and another GradeBook class (does calculations) on another page. How do I connect the two pages together?
For example: If the studentName is 'Andrew' and it is found in studentNameArray, and I select 1 for which test score I want to see (scoreOneArray), say the number 88. My program finds 'Andrew' and '88'. What it does not do is send 'Andrew' and '88' to GradeBook to have the data compute test percentage (88/100) and find the corresponding letter grade (in this case 'B'). Lastly, then print students name, test score (88%), and the letter grade.
Program (main):
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
double test1Calculation;
double test2Calculation;
double test3Calculation;
double test4Calculation;
int i, j, k, l;
int testOneSum = 0;
int testTwoSum = 0;
int testThreeSum = 0;
int testFourSum = 0;
int checker = 0;
int index=0;
String choice;
Scanner students = new Scanner(new File("names.txt"));
Scanner TestOne = new Scanner(new File("testOne.txt"));
Scanner TestTwo = new Scanner(new File("testTwo.txt"));
Scanner TestThree = new Scanner(new File("testThree.txt"));
Scanner TestFour = new Scanner(new File("testFour.txt"));
String token1 = "";
List<String> studentName = new ArrayList<>();
while (students.hasNext()) {
// find next line
token1 = students.next();
studentName.add(token1);
}
String[] studentNameArray = studentName.toArray(new String[0]);
List<Integer> scoreOne = new ArrayList<>();
// while loop
while (TestOne.hasNext()) {
// find next line
Integer token2 = TestOne.nextInt();
scoreOne.add(token2);
}
Integer[] scoreOneArray = scoreOne.toArray(new Integer[0]);
List<Integer> scoreTwo = new ArrayList<>();
// while loop
while (TestTwo.hasNext()) {
// find next line
Integer token3 = TestTwo.nextInt();
scoreTwo.add(token3);
}
Integer[] scoreTwoArray = scoreTwo.toArray(new Integer[0]);
List<Integer> scoreThree = new ArrayList<>();
// while loop
while (TestThree.hasNext()) {
// find next line
Integer token4 = TestThree.nextInt();
scoreThree.add(token4);
}
Integer[] scoreThreeArray = scoreThree.toArray(new Integer[0]);
List<Integer> scoreFour = new ArrayList<>();
// while loop
while (TestFour.hasNext()) {
// find next line
Integer token5 = TestFour.nextInt();
scoreFour.add(token5);
}
Integer[] scoreFourArray = scoreFour.toArray(new Integer[0]);
for (i = 0; i < scoreOneArray.length; i++)
testOneSum += scoreOneArray[i];
test1Calculation = (double) testOneSum / 5;
for (j = 0; j < scoreTwoArray.length; j++)
testTwoSum += scoreTwoArray[j];
test2Calculation = (double) testTwoSum / 5;
for (k = 0; k < scoreThreeArray.length; k++)
testThreeSum += scoreThreeArray[k];
test3Calculation = (double) testThreeSum / 5;
for (l = 0; l < scoreFourArray.length; l++)
testFourSum += scoreFourArray[l];
test4Calculation = (double) testFourSum / 5;
System.out.println("The average for test one is: " + test1Calculation);
System.out.println("The average for test two is: " + test2Calculation);
System.out.println("The average for test three is: " + test3Calculation);
System.out.println("The average for test four is: " + test4Calculation);
Scanner studentSearch = new Scanner(System.in);
System.out.println("Enter student name : ");
String foundStudent = studentSearch.nextLine();
boolean found = Arrays.stream(studentNameArray).anyMatch(t -> t.equals(foundStudent));
if (found) {
index++;
System.out.println(foundStudent + " is found.");
//menu loop
do {
//displayed user options
System.out.println("1. To find score for first test");
System.out.println("2. To find score for second test");
System.out.println("3. To find score for third test");
System.out.println("4. To find score for fourth test");
//menu choices
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter your choice: ");
choice = keyboard.next();
if (choice.equals("1")) {
int score= scoreOneArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("2")) {
int score= scoreTwoArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("3")) {
int score= scoreThreeArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("4")) {
int score= scoreFourArray[index];
System.out.println(score);
checker = -1;
} else {
//Error message
System.out.println("invalid choice");
}
}
while (checker != -1);
} // End of Menu Method
else {
System.out.println(foundStudent + " is not found.");}
students.close();
TestOne.close();
TestTwo.close();
TestThree.close();
TestFour.close();
}
}
Calculations(GradeBook):
import java.util.ArrayList;
public class GradeBook {
private char[] letterGrade = {'A', 'B', 'C', 'D', 'F'};
private ArrayList<String> names = new ArrayList<>();
private double [][] scores = new double[5][4];
public GradeBook(ArrayList<String> studentNames, double[][] studentScores){
this.names = studentNames;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 4; j++){
scores [i][j] = studentScores[i][j];
}
}
}
public String getName(int studentIndex){
return names.get(studentIndex);
}
public double getAverage(int studentIndex){
double total = 0;
for (int i = 0; i < 4; i++){
total += scores[studentIndex][i];
}
return (total / 4);
}
public char getLetterGrade(double avgScore){
if (avgScore >= 90 && avgScore <= 100){
return letterGrade[0];
}
else if (avgScore >= 80 && avgScore <= 89){
return letterGrade[1];
}
else if (avgScore >= 70 && avgScore <= 79){
return letterGrade[2];
}
else if (avgScore >= 60 && avgScore <= 69){
return letterGrade[3];
}
else if (avgScore >= 0 && avgScore <= 59){
return letterGrade[4];
}
return ' ';
}
public void getStudent(){
for (int i = 0; i < names.size(); i++){
System.out.println("\nStudent #" + (i+1)
+"\n\t\tName: " + names.get(i)
+"\n\t\tAverage: " + getAverage(i) + "%"
+"\n\t\tLetter Grade: " + getLetterGrade(getAverage(i))
+"\n\n");
}
}
}
I don't understand how much of what's going on in GradeBook relates to what you're doing in your main function. I see how in your main you're coming up with a single score based on the user's selection of a student and a test number. But once you have this user and score, I don't see how that matches up with the data in the double[][] studentScores table contained in GradeBook. What is that data? Where does it come from?
Your code in main seems to have a significant problem. index will always be 1 by the time it's used. Its value is not affected by what is entered as a student name. I think you mean for it to be. Also, I don't understand how the single integer score you come up with in main matches up with the avgScore accepted by the GradeBook. But ignoring all of that...
It seems like you'd have just a single GradeBook, right? So I think you'd instantiate just a single instance of it, and then you could use it to look up the student's name and to calculate the grade based on the student's score. Assuming that index matched up with the names list in GradeBook, and you somehow computed an averageScore, that would look something like this...
public class Main {
public static void main(String[] args) throws IOException {
...
GradeBook gradeBook = new GradeBook(...);
...
while (...) {
index = ...
...
averageScore = ...
...
studentName = gradeBook.getName(index);
grade = gradeBook. getLetterGrade(averageScore);
System.out.println(String.format("Student: %s. Grade: %s", studentName, grade));
}
The other use case I can see is that you'd calculate somehow calculate the studentScores table from the data you read in main, and then you could create a GradeBook with that to have it display all of that information. That would look like this...
studentScores = ...
...
GradeBook gradeBook = new GradeBook(studentScores);
gradeBook.getStudent()

Some problems with my array

my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

While loop not working

Hi I am fairly new to java and trying to familiarize myself to it by doing some exercises online.
How do i properly code the while loop so that everytime the user input is wrong it asks the same question again and does not proceed to the next line of code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
boolean checker = true;
while (checker){
for (int i = 0; i < entries; i++){
int input;
int addToList;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
grade.add(input);
if (input >= 0 && input<= 100) {
}else {
System.out.println("invalid input try again..");
checker = false;
}
}
}
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade){
sum+= grades;
}
mean =(double)sum/count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
Your logic is backwards. You want the loop to continue if the input is incorrect. There are two ways to fix this:
Change while(checker) to while(!checker)
Change checker=false to checker=true after printing the error message. And set checker=false in the if branch.
It might help if you change the name of your checker variable to something that reads more directly. For example isInputCorrect reads very nicely when you write while(!isInputCorrect) and it also makes it more clear what the values of true and false represent.
try this :
boolean checker = true
for(int i=0;i< entries;i++){
int input;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
while(checker){
if(input >= 0 && input<= 100){
grade.add(input);
checker = false;
}else{
System.out.println("invalid input try again..");
}
}
checker = true;
}
You could try this
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
for (int i = 0; i < entries; i++) {
int input;
do{
input = dataIn.nextInt();
if (input >= 0 && input <= 100) {
grade.add(input);
}else{
System.out.println("invalid input try again..");
}
}while(!(input >= 0 && input <=100));
}
dataIn.close();
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade) {
sum += grades;
}
mean = (double) sum / count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
instead of doing while(checker)
make a loop for while(running)
then send it to the keyboard.nextInt()
if its the wrongAnswer than it will loop, if its correct than set running to false
and have code that follows the while loop

Taking same output twice times

/*
* (Sort students) Write a program that prompts the user to enter the number of students,
*the students’ names, and their scores, and prints student names in decreasing
*order of their scores.
*/
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
When i run this program;
run:
Enter number of students: 3
Enter the name of student:
Enter the name of student:
a
Enter the name of student:
b
Enter the score of student:
c
Exception in thread "main" java.util.InputMismatchException
// i got " Enter the name of student: " twice times instead of one.
The first thing that comes to mind (not sure if it is correct here) is that you type the number of students and press "enter". It reads the first int (the 3) and reads the "enter" as the first input for the first student.
Maybe try int numberOfStudents = Integer.ParseInt(input.nextLine());?
That way the newline wont be added to the students.
You just have to remove the first System.out.print("Enter number of students: "); as you are printing the phrase in your for loop for every student. Therefore you are printing it twice for the first student (one time before your loop and one time in your loop)
It's not a good idea to answer homework question in SO. But since you have tried some code, It's OK to answer the Q. Take a look:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}

Categories