How can I prevent the user from entering the same text twice - java

This program basically calculates the gpa, by letting the user enter the number of courses and course code, with the relevant credit and marks. If the course code is entered twice, a message will show (the course is already registered), and it will keep looping until the user has entered all courses with a different course code
I have created two methods. One to check if the code is already registered and the other for calculating the gpa, the first method that checks the user input, I'm not sure about it. Because if I entered the course code twice it will only show the message and would allow me to calculate the rest
public static boolean checkCourse(String[] courseList, String code){
boolean check = false;
for(int i=0 ; i < courseList.length; i++){
if(code.equals(courseList[i]))
check = true;
else
check = false;
}
return check;
}
public static double gradeValue(double marks){
double grade = 1.0;
if(marks >=95){ grade = 5.0;}
else if (marks >= 90) { grade = 4.75;}
else if (marks>=85) { grade = 4.5;}
else if (marks >= 80) { grade = 4.0;}
else if (marks >= 75) { grade = 3.5; }
else if (marks >= 70) { grade = 3.0;}
else if (marks >= 65) {grade = 2.5 ;}
else if (marks >= 60) { grade = 2;}
else if (marks < 60) { grade =1 ;}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit=0;
int sumOfmarks =0;
for(int i =0; i<Courses.length;i++){
System.out.print("Enter a course code: ");
Courses[i] = input.next();
if(checkCourse(Courses,Courses[i])){
System.out.println("the course already registered");
i--;
}
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks +=marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks /sumOfcreadit;
System.out.println("The GPA is: "+gradeValue(TotalMarks));
}

I made some changes in your code and now it works. Changes are described in below code. There was 3 important changes.
I tried to make as less changes as possible to make your code work as expected
public static boolean checkCourse(String[] courseList, String code) {
boolean check = false;
for (int i = 0; i < courseList.length; i++) {
if (code.equals(courseList[i])) { // equals instead of == to compare strings
check = true;
break; // you have to break loop if it is true because else statement before returned false even if there was the same course code due to null values in next array elements which was not filled yet
}
}
return check;
}
public static double gradeValue(double marks) {
double grade = 1.0;
if (marks >= 95) {
grade = 5.0;
} else if (marks >= 90) {
grade = 4.75;
} else if (marks >= 85) {
grade = 4.5;
} else if (marks >= 80) {
grade = 4.0;
} else if (marks >= 75) {
grade = 3.5;
} else if (marks >= 70) {
grade = 3.0;
} else if (marks >= 65) {
grade = 2.5;
} else if (marks >= 60) {
grade = 2;
} else if (marks < 60) {
grade = 1;
}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit = 0;
int sumOfmarks = 0;
for (int i = 0; i < Courses.length; i++) {
System.out.print("Enter a course code: ");
String code = input.next();
if (checkCourse(Courses, code)){
System.out.println("the course already regestered ");
i--;
continue; // continue is neccessary to let user write value again if it already exists
}
Courses[i] = code;
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks += marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks / sumOfcreadit;
System.out.println("The GPA is: " + gradeValue(TotalMarks));
}

Use a set kind of structure to store all the course code visited, It will avoid unnecessary iteration on your course array
this method can be enhanced to
public static boolean checkCourse(HashSet<String> courses, String code){
boolean check = false;
if(courses.contains(code)){
check = true;
else
check = false;
}
return check;
}
Initialise the hashset courses and if the checkCourses method returns false add the course code in courses.
Initialize before loop like this
HashSet<String> courseSet = new HashSet<String>();
your if condition inside loop
if(checkCourse(courseSet,courses[i])){ // check for variable name , name should always start with lower case letter
System.out.println("the course already regestered ");
i--;
// You can use continue if you don't want processing for it
// it will skip the loop iteration and it will go next iteration
}else{
courseSet.add(courses[i]);
}

Related

do while loop is not breaking properly java

public class DoWhile1 {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum/total;
}
}
This loop is suppose to break when 999 is entered, but when entered before breaking it output error message from the else inside the loop. It's not suppose to output anything before breaking.
we tried moving the while part of the loop, but it did not affect anything. We can't see any other problems with it.
Your do-while is working correctly - the course of action is the following:
In a do-while, the statements are always executed at least once. So you enter the do { }, and fall into the else condition, since 999 is greater than 0 and not smaller than 100.
You then evaluate the expression grade != 999 -> this is false, since grade == 999.
You don't do the do { } again and come out of the do-while.
To achieve the behavior that you want, you will need to add an additional statement inside the do { }, e.g:
...
if (grade == 999) {
break; //or print statement
}
else if (grade >= 0 && grade <= 100) {
...
You could wrapp the message by another if that checks if the number is not 999.
else
{
if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
}
Change else to else if (grade != 999) when you are displaying the error.
Do it as follows:
import java.util.Scanner;
public class Main {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum / total;
}
}
A sample run:
Please enter a grade b/w 0-100:
24
Please enter another grade or 999 to break:
Please enter a grade b/w 0-100:
999
You could check input value for grade == 999 and exist in case it equals to:
public static double getAverage() {
try (Scanner scan = new Scanner(System.in)) {
int total = 0;
int sum = 0;
int average = 0;
while (true) {
System.out.print("Please enter a grade b/w 0-100 (or 999 to exit): ");
int grade = scan.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum += grade;
} else if (grade == 999)
break;
else
System.out.println("Incorrect value\n");
}
return (double)sum / total;
}
}

Write a program that reads student scores, gets the best score, and then assigns grades

Can someone please tell me why my code is not providing the correct output? Here aare the instructions "
I need to write a program that reads student scores, gets the best
score, and then assigns grades based on the following scheme:
1) Grade is A if score is >= best - 10
2) Grade is B if score is >= best - 20;
3) Grade is C if score is >= best - 30;
4) Grade is D if score is >= best - 40;
5) Grade is F otherwise.
The program prompts the user to enter the total number of students, then prompts the user to enter all of the scores, and concludes by displaying the grades. My problem comes from pulling the grades from an array, this is what I have so far:
// Here is my code. Thank You
import java.util.Scanner; // imports the scanner function
public class NBpractice { //class is formed
public static void main(String []args) { // main method
// user input is asked for the number of students
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int studentNum = input.nextInt();
//user input is asked for students scores
Scanner input2 = new Scanner(System.in);
System.out.print("Enter " + studentNum + " scores: ");
int scores = input2.nextInt();
int best = 80;
char letterGrade;
int scoresArray[] = new int[studentNum]; // array is created and holds the # of place values as students
for (int i = 0; i < scoresArray.length; i++) { // for loop created
scoresArray[i] = input2.nextInt(); //array values are assigned to user's input
best = scoresArray[0];
if (best < scoresArray[i]) {
best = scoresArray[i];
}
//-----------------------------------------------------------------------------
if (scores >= (best - 10)) {
letterGrade = 'A';
}
else if (scores >= (best - 20)) {
letterGrade = 'B';
}
else if (scores
>= (best - 30)) {
letterGrade = 'C';
}
else if (scores >= (best - 30)) {
letterGrade = 'D';
}
else {
letterGrade = 'F';
}
System.out.println("Student " + i + " Score is " + scoresArray[i] + " and grade is: " + letterGrade );
}
//------------------------------------------------------------
}
}
Some pointers...
This: System.out.print("Enter " + studentNum + " scores: "); and int scores = input2.nextInt(); need to go in the for loop body.
Use the for loop to populate the array.
Once that the for loop is executed, find the best (highest) score in the array.
Use another for loop to sort out the grades.
As is, your program will only ask for the grades and pretty much assumes that the best grade is 80, which might not always be the case.
You'll need two separate for loops. One to read the grades, and get the best, and the second for loop to normalize the grades.
int[] scores = new int[amount];
int best = -1;
for(int i = 0; i < amount; i++)
{
scores[i] = in.nextInt();
if(scores[i] > best)
best = scores[i];
}
System.out.println(Arrays.toString(scores));
// Now that we have the best, we can normalize
// the rest of the scores based on the best
// and assign the corresponding letter grade.
String[] grades = new String[amount];
for(int i = 0; i < amount; i++)
{
int score = scores[i] * 100 / best;
if(score >= 90)
grades[i] = "A";
else if(score >= 80)
grades[i] = "B";
else if(score >= 70)
grades[i] = "C";
else if(score >= 60)
grades[i] = "D";
else
grades[i] = "F";
scores[i] = score;
}
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(grades));
Test input 80 60 75 83 67 outputs:
[80, 60, 75, 83, 67]
[96, 72, 90, 100, 80]
[A, C, A, A, B]
I would recommend using a Student class and not work with parallel lists or arrays. A Student class can for example look like this:
class Student {
int score;
String grade; // could also be an Enum
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score;
}
public String getGrade() {
return this.grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" + "score=" + score + ", grade='" + grade + '\'' + '}';
}
}
You can then make instance of the Students and add them to an ArrayList in you public static void main.
I think you have to use two loops because you cannot know beforehand what the best grade will be. In your main you can make enter the students add them to a List and compare their grades;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int highScore = 0;
int numOfStudent = input.nextInt();
List<Student> studentList = new ArrayList<>();
for (int i = 1; i <= numOfStudent; i++) { // you might want to add Exception handling here, by surrounding it with a try / catch or do more checks than only i <= numOfStudent
System.out.printf("please fill in the score of student no %d \n", i);
int score = input.nextInt();
Student student = new Student();
student.setScore(score);
if (score > highScore) {
highScore = score;
}
studentList.add(student);
}
System.out.println("these are the scores and grades of the Students");
for (Student s : studentList) {
if (s.getScore() >= highScore - 10) {
s.setGrade("A");
}
else if (s.getScore() >= highScore - 20) {
s.setGrade("B");
}
else if (s.getScore() >= highScore - 30) {
s.setGrade("C");
}
else if (s.getScore() >= highScore - 40) {
s.setGrade("D");
}
else {
s.setGrade("F");
}
System.out.println(s);
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_1 {
public static void main(String[] args) {
// Assign grades
Scanner input = new Scanner(System.in);
int numStudents;
int[] scores;
int best;
System.out.println("Enter the number of students: ");
numStudents = input.nextInt();
scores = new int[numStudents];
System.out.println("Enter " + numStudents + " scores: ");
for (int i = 0; i < numStudents; i++) {
scores[i] = input.nextInt();
}
displayGrades(findBestScore(scores), scores);
}
public static int findBestScore(int[] scores) {
int best = scores[0];
for (int i = 1; i < scores.length-1; i++) {
if (scores[i] > best)
best = scores[i];
}
return best;
}
public static void displayGrades(int best, int[] scores ) {
char grade = ' ';
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= best-10)
grade = 'A';
else if (best - 10 > scores[i] && scores[i] >= best - 20)
grade = 'B';
else if (best - 20 > scores[i] && scores[i] >= best -30)
grade = 'C';
else if (best - 30 > scores[i] && scores[i] >= best -40)
grade = 'D';
else if (best - 40 > scores[i])
grade = 'F';
System.out.println("Student " + i + " score is " + scores[i] + " and grade is " + grade);
}
}
}

How do I properly pass a scanner and an int into a function and return the integer value in java?

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.

Scanner only reads for loop once? - Java

I'm trying to make a class where you input any number of grades (A-F) and calculates the GPA and returns the GPA and eligibility to extracurricular activities. It seems like the scanner only allows one input, then prints the GPA and eligibility.
So far this is what I have:
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
double myGPA;
int myNumClasses;
double myValue;
Scanner sc = new Scanner(System.in);
System.out.println("Press any other lettter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
myValue = 0;
myNumClasses = 0;
myGPA = 0;
for (String next = sc.next(); input.equalsIgnoreCase("a") || input.equalsIgnoreCase("b") ||
input.equalsIgnoreCase("c")|| input.equalsIgnoreCase("d") || input.equalsIgnoreCase("f"); next = sc.next())
{
if (input.equalsIgnoreCase("a"))
{
myValue += 4.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("b"))
{
myValue += 3.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("c"))
{
myValue += 2.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("d"))
{
myValue += 1.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("f"))
{
myNumClasses += 1;
}
myGPA = myValue / myNumClasses;
if (myGPA >= 2.0 && myNumClasses >= 4)
{
System.out.println("Eligible");
}
else if (myNumClasses < 4)
{
System.out.println("Ineligible, taking less than 4 classes");
}
else if (myGPA >= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa above 2.0 but has F grade");
}
else if (myGPA <= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa below 2.0 and has F grade");
}
else if (myGPA < 2.0)
{
System.out.println("Inelligible, gpa below 2.0");
}
System.out.println("Your GPA = " + myGPA);
}
}
}
// It looks like your missing a for loop. I just copied some of your
//code and ran it through a for loop. The rest of the code is kind of unclear.
System.out.println("Enter the number of grades you will enter: ");
int userAns = sc.nextInt();
for (int index = 0; index <= userAns; index++)
{
System.out.println("Press any other letter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
}

Boolean and if/else statement help in Java

I'm trying to have a user enter an input (their name and age, obviously) and if they're younger than 10 or older than 100, I want it to return back to the start and ask them for their age again, until the condition has been met, and then go on to ask the users name. I know how to do that, a boolean. What I don't know how to do is to implement that into my if/else statements. Could anyone help me?
public class Person {
public static void main(final String[] args) {
int age;
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
} else if (age > 100) {
System.out.println("How old are you really?");
}
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter in your name");
name = in.nextLine();
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}
}
Use a while loop while the condition is not met:
boolean conditionMet = false;
while(!conditionMet) {
// ...
else if (age >= 18 && age <= 100) {
System.out.println("So you're an adult, huh?");
conditionMet = true; // the condition is met => exit the loop
}
// ...
}
Just put a while loop around your first scan and if statements.
boolean validAge = false;
while (!validAge) {
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
validAge = true;
} else if (age > 100) {
System.out.println("How old are you really?");
}
}
You need a loop:
boolean ageIsCorrect = false;
while (!ageIsCorrect) {
// ask age, if the age is correct, set ageIsCorrect to true
}
Put it inside a while loop
while(age is between your specified critiera)
Roughly something like this:
private static int readAndCheck() {
// read age and validate, upon failure return -1
}
public static void main(final String[] args) {
int age = -1;
while (age == -1) {
age = readAndCheck();
}
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}
You should do that in a while loop. I think it's easier and better than other answers:
int age = 0;
while (age<10 || age>100){
age = scan.nextInt();
}
string username = scan.next();
...
Since you are looping, put the prompting code in a loop. Use a boolean to exit the loop
boolean goodAnswer = false;
do
{
System.out.println("Enter in your age.");
...
if ((age >= 10) && (age 100)
{
... // do not set goodAnswer, because the answer was not good
}
} while (!goodAnswer);
Your code actually needs to be better encapsulated to check the age.
Use a method called isValidAge(age) to return a true or false result and then you can write:
int age = 0;
while(!isValidAge(age)){
System.out.println("Please try again! Not a valid age (for an adult)");
... read in the age using scanner...
}
Generally speaking if else () statements are messy and don't extend well - maintenance wise they are not always the best option.

Categories

Resources