I did everything as far as concepts. I made my class, and my client class. The assignment is to make a program that allows the user to input 10 grades into a gradebook, and get the max, min, and average grade of class.
My only problem is I want to make sure the user cannot put anything in the program that is not an integer; do I put instructions like that in my class or client java doc?
This is my class:
import java.util.Arrays;
public class ExamBook{
int grades[];
int classSize;
int MIN = 0;
int MAX = 100;
public ExamBook(int[] gradeBook)
{
classSize = 10;
//instantiate array with same length as parameter
grades = new int[gradeBook.length];
for ( int i = 0; i <= gradeBook.length-1; i++ )
{
grades[i] = gradeBook[i];
}
Arrays.sort(grades);
}
//setter, or mutator
public void setClassSize( int newClass )
{
classSize = newClass;
}
//get return method
public int getClassSize()
{
return classSize;
}
//calculate highest grade
public int calculateMaxGrade()
{
int max = grades[0]; //assuming that the first index is the highest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] > max )
max = grades[i]; //save the new maximum
}
return max;
}
//calculate lowest grade
public int calculateMinGrade()
{
int min = grades[0]; //assuming that the first element is the lowest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] < min)
min = grades[i]; //save the new minimum
}
return min;
}
//calculate average
public double calculateAverageGrades()
{
double total = 0;
double average = 0;
for ( int i = 0; i < grades.length; i++ )
{
total += grades[i];
}
average = total/grades.length;
return average;
}
//return an assorted array
public int[] assortedGrades()
{
Arrays.sort(grades);
return grades;
}
//return printable version of grades
#Override
public String toString()
{
String returnString = "The assorted grades of the class in ascending order is this: " + "\t";
for ( int i = 0; i <= grades.length - 1; i++ )
{
returnString += grades[i] + "\t";
}
returnString += " \nThe class average is a/an " + calculateAverageGrades() + "." + "\nThe highest grade in the class is " + calculateMaxGrade() + "." + "\nThe lowest grade in the class is " + calculateMinGrade() + ".";
returnString += "\n";
return returnString;
}
}
**This is my client:**
import java.util.Scanner;
import java.util.Arrays;
public class ExamBookClient
{
public static ExamBook classRoom1;
public static void main( String[] args)
{
int MAX = 100;
int MIN = 0;
Scanner scan = new Scanner(System.in);
//create array for testing class
int[] grading = new int [10];
System.out.println("Please enter 10 grades to go into the exam book.");
if(scan.hasNextInt())
{
for (int i = 0; i < grading.length; i++)
{
int x = scan.nextInt();
if( x>MIN && x<MAX)
{
grading[i] = x;
}
}
}
classRoom1 = new ExamBook (grading);
System.out.println("The classroom size is " + classRoom1.getClassSize() + "."
+ "\n" + classRoom1.toString() + ".");
}
}
Prompt for scan.hasNextInt() in your for loop of your client instead of outside the for loop. Like this:
boolean failed = false;
for (int i = 0; i < grading.length; i++)
{
if (failed)
scan.nextLine();
failed = false;
if (scan.hasNextInt()) {
int x = scan.nextInt();
if(x >= MIN && x <= MAX)
{
grading[i] = x;
} else {
System.out.println("Grade must be from 0-100!");
i--;
continue;
}
} else {
// jump back to the start of this iteration of the loop and re-prompt
i--;
System.out.println("Number must be an int!");
failed = true;
continue;
}
}
You might want to do this in two parts - your API should specify that it works with only integers - perhaps the method which processes the grades will accept Integer arguments only. The parser of the String can specify in its Javadocs what it does when the argument passed to it is not an integer. You client should also validate that the input is an integer (maybe within the valid range). If the user input is incorrect, then maybe it can display a usage manual.
You can check using the below code. If you pass other than number it would throw NumberFormatException
public static boolean checkIfNumber(String input) {
try {
Integer in = new Integer(input);
} catch (NumberFormatException e) {
return false;
}
return true;
}
You can change this part as follows. This way the user can enter non-integers but in those cases you will print out warnings and you will ignore them.
System.out.println("Please enter 10 grades to go into the exam book.");
int i = 0;
int x = -1;
while (scan.hasNext() && i < 9) {
String sx = scan.next();
try {
x = Integer.parseInt(sx);
i++;
if (x > MIN && x < MAX) {
grading[i] = x;
}
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
classRoom1 = new ExamBook(grading);
Chech this link, it has the solution.
You must use the method hasNextInt() of Scanner.
If you do not want to use exceptions you can always use a Regex match to check that what you have in the string is a number valid for you.
Bearing in mind that your valid numbers are between 0 and 100, and 0 and 100 are not included seeing you code, the reg ex will be:
s.matches("[1-9][0-9]{0,1}")
Basically what this means is that you are going to have a character that is a number between 1 and 9 as first char, and then you could have one between 0 and 9, this way you do not allow 0 at the beginning (01 is not valid) and 0 by it self is also not valid. 100 has 3 chars so is not valid neither.
Related
This program is supposed to find the maximum, minimum, and average of grades. User inputs int inputGrade and the program displays letter it is. It's supposed to do this how however many students are needed. I'm having trouble writing the method where it finds the max and min. (yes I've talked to my teacher if anyone's wondering...) I pasted the methods below (they don't work). Just like IN GENERAL, does anyone know how to find the maximum and minimum of a set of entered numbers? (not using arrays, lists, or any unusual imports other than scanner) ** note I've updated this a lot...
import java.util.Scanner;
public class GetLetterGrade
{
static int inputGrade; // input grade
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
int classAverage;
int classMin; // class's minimum grade
int classMax; // class's maximum grade
while (inputGrade != -1) // while user is entering grades
{
System.out.println("Welcome to the grade calculator. \nPlease enter a
numeric grade. After the last student in the class, enter a grade of
-1.");
inputGrade = reader.nextInt();
letterGrade(inputGrade); // calls letter grade method
findMaxAndMin();
result();
}
}
// find letter grade
public static String letterGrade(int numGrade)
{
String gradeMessage = "";
{
if (numGrade >= 96 && numGrade <= 100) // if numeric grade is 96-100 then
it's A+
{
gradeMessage = "That's an A+.";
result();
// DOES THIS FOR GRADES A+ TO F, NOT SHOWN, too much to paste!
}
}
}
return gradeMessage;
}
public static int findCharGrade(int numGrade)
{
char letter;
if (numGrade >= 90 && numGrade <= 100) // A
{
letter = 'A';
}
else if (numGrade >= 80 && numGrade < 90) // B
{
letter = 'B';
}
else if (numGrade >= 70 && numGrade < 80) // C
{
letter = 'C';
}
else if (numGrade >= 60 && numGrade < 70) // D
{
letter = 'D';
}
else if (numGrade < 60) // F
{
letter = 'F';
}
}
// finds maximum and minimum grades
public static int findMaxAndMin(int inputGrade)
{
int max = Math.max(inputGrade, max);
int min = Math.min(inputGrade, min);
if (inputGrade < max)
{
inputGrade = max;
findCharGrade(inputGrade);
}
else if (inputGrade > min)
{
inputGrade = min;
findCharGrade(inputGrade);
}
}
public static void calcAverage(int sumOfGrades, int numOfStudents)
{
// something goes here
}
// finds results
public static void result()
{
int min = findMaxAndMin(inputGrade);
int max = findMaxAndMin(inputGrade);
System.out.println("Please enter a numeric grade");
int inputGrade = reader.nextInt();
letterGrade(inputGrade);
if (inputGrade == -1)
{
System.out.println("You entered " + numOfStudents + " students. Class
Average: " + average + " Class Minimum: " + min + " Class maximum: " + max
+ " \nThanks for using the class grade calculator!");
}
}
here is a more simplistic way of doing it not using Lists or arrays
double sum = 0; // use double so that you do not do integer arithmetic
int count = 0;
int min = Integer.MAX_VALUE; // set to very high value
int max = Integer.MIN_VALUE; // set to bery low value
Scanner scan1 = new Scanner(System.in);
System.out.println("enter numbers (-1 to quit");
while (scan1.hasNextInt()) {
int i = scan1.nextInt(); // get the number (assuming only int value)
if (i == -1) break;
min = Math.min(i, min);
max = Math.max(i, max);
sum += i;
count++;
}
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + sum / count);
}
disclaimer
This code will not handle wrong type of input e.g. Strings
edit
If you want the average to be calculated in a separate method you can have a method like
double calcAvg (double sum, int count) {
return sum / count;
}
this can then be called as
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + calcAvg (sum, count));
}
You can (and should) divide your problem into the smaller methods.
I'll drop the code, and you read and study it.
I admit I haven't pay to much attention of this simple quest, but still...
Here you are:
import java.util.List;
public class Answer {
public static void main(String[] args) {
//test with some grades (integers)
Answer answer = new Answer();
List<Integer> someGrades = List.of(12, 66, 34, 96, 3, 77, 2);
System.out.println("max = " + answer.findMaxGrade(someGrades));
System.out.println("min = " + answer.findMinGrade(someGrades));
System.out.println("avg = " + answer.findAverageGrade(someGrades));
}
private int findMaxGrade(List<Integer> grades) {
int max = Integer.MIN_VALUE;
for (int grade : grades) {
if (grade > max) max = grade;
}
return max;
}
private int findMinGrade(List<Integer> grades) {
int min = Integer.MAX_VALUE;
for (int grade : grades) {
if (grade < min) min = grade;
}
return min;
}
private double findAverageGrade(List<Integer> grades) {
double average = 0;
for (int grade : grades) {
average += grade;
}
return average / grades.size();
}
}
package example;
import java.util.Scanner;
class Example {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int m = 1, total = 0, max = 0, min = 100;
double avg = 0;
while (m <= 5) {
System.out.print("Input marks " + m + " = ");
int inp = r.nextInt();
total += inp;
m++;
min=min<inp?min:inp;
max=max<inp?inp:max;
}
avg = (double)(total) / 5;
System.out.println("Total : " + total);
System.out.println("Max : " + max);
System.out.println("Min : " + min);
System.out.println("Average : " + avg);
}
}
I know how to create the array as i did below. But how would i check if the user inputed the same number. I tried using if statements but i kept getting errors. I also tried using a do while.
I have to write a program that generates and stores 20 random numbers in the array Data[] and asks the user to enter their guess which i did. If their number appears in the array, they get 2 points for each occurrence, the array is printed and all positions where the lucky number can be found. If it doesn't appear in the array, I have to print the lowest and highest values of the array and allow only one more try. if the player gets it right the second time they get 1 point for each appearance.
int lucky;
int Data[]= new int[20];
for(int i=0;i<Data.length;i++){
Data[i]=(int)(Math.random()*100);
}
for(int i=0;i<Data.length;++i){
System.out.println(Data[i]+"\t");
}
String input1=JOptionPane.showInputDialog("Enter your lucky number");
lucky=Integer.parseInt(input1);
System.out.println(lucky);
Something like this should work as you expect to see if the value exists in the array, it can be expanded to search and find for high/low values:
int counter = 0; //Assume not found at first
for (int i: Data) {
if (i==Integer.parseInt(input1)){
counter++;
}
}
System.out.println("The numer was found "+Integer.toString(counter)+" time(s).");
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] data = new int[20];
int guess;
int times;
int score = 0;
int tries = 0;
fillArrayWithRandoms(data);
while (tries < 2) {
System.out.print("Guess a number: ");
guess = sc.nextInt();
if ((times = timesInArray(guess, data)) != 0) {
if (tries == 0)
score += 2 * times;
else
score += times;
printArray(data);
fillArrayWithRandoms(data);
System.out.println("You are lucky! Score: " + score + "\n");
} else {
tries++;
System.out.println("You are unlucky!");
if (tries < 2)
printBoundaries(data);
System.out.println();
}
}
System.out.println("Game Over! Your score: " + score);
}
private static void printArray(int[] data) {
for (int element : data) {
System.out.print(element + " ");
}
System.out.println();
}
private static void fillArrayWithRandoms(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (int) (Math.random() * 100);
}
}
private static int timesInArray(int guess, int[] data) {
int occurrence = 0;
for (int element : data) {
if (element == guess)
occurrence++;
}
return occurrence;
}
private static void printBoundaries(int[] data) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int element : data) {
if (element < min) {
min = element;
}
if (element > max) {
max = element;
}
}
System.out.println("Try a number between " + min + " and " + max);
}
}
I'm making a program that counts the frequency of letters from a user-entered string, and have recently encountered the 'Arithmetic Exception' error.
I cannot for the life of me figure out what's causing it, even though I know it's because something is being divided by 0.
Here's my code:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
I know that I only have ABC and M in at the moment but was gonna work those in later.
This is the first time i've posted on here and i'm still newish to Java so any help whatsoever is greatly appreciated!
I ran it and it says line 67. here is the total:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
To fix:
double occ = (number > 0) ? number/input * 10 : 0;
This sets occ to 0 in case of number being set to 0. Good luck.
Hope this helps.
The line of code causing the error is in your method:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
The input variable is declared in your class here:
Line 6: public static int input;
Since you didn't initialize it nor does the value is being changed in your codes, the value of input remains as 0 through out the entire program. (Default value for an uninitialized int variable is 0)
Since it is always 0, you are always dividing a number with 0.
double occ = number / 0*10;
Basically I need to write a program that takes user input up to and including 2^31 -1 in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
or
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help?
This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
Sorry, the code formatted weirdly in the textbox.
value = value % 10;
Probably the end-all-be-all of your problems.
If value is 2034, then value % 10 returns 4... and then assigns that value to value, you go through your if else block, then do 4/10 get 0, and exit the while loop without addressing the other 3 digits.
I suggest something more like this:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.
value = value % 10;
This statement will override your original value with a reminder i.e value % 10.
If value = 2034 and value % 10 = 4, then value = 4 which isn't what you want.
Instead use a temporary variable
int lastDigit = value % 10;
Then your code becomes;
while (value > 0) {
int lastDigit = value % 10;
if (lastDigit==0)
{
zeroCount++;
}
else if (lastDigit%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
import java.util.Scanner;
public class oddEvenZero
{
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null)
{
int k= sarray.length-1;
int intarray[] = new int[k];
for (int i = 1; i < sarray.length; i++) {
intarray[i-1] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String value;
System.out.print("Enter an integer: ");
value = scan.next();
String words[] = value.split("");
oddEvenZero obj = new oddEvenZero();
try{
int intarray[]= obj.convertStringArraytoIntArray(words);
int even_number =0;
int odd_number =0;
int zero_number =0;
for (int h: intarray)
{
if(h==0)
{
zero_number++;
}
else if(h%2==0)
{
even_number++;
}
else{
odd_number++;
}
}
System.out.println("even numbers are"+ even_number);
System.out.println("odd numbers are"+odd_number);
System.out.println("Zero numbers are"+zero_number);
}
catch(Exception ex)
{
System.out.println("Please enter number");
}
}
}
If some of you are still unable to figure this code out, I found this while searching around for a bit, and works just fine:
import java.util.*;
public class Java_1
{
public static void main (String[] args)
{
String string;
int zero = 0, odd = 0, even = 0, length, left = 0;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter any positive number: ");
string = scan.next();
length = string.length();
while (left < length)
{
string.charAt(left);
if (string.charAt(left) == 0)
zero++;
else if (string.charAt(left) % 2 == 0)
even++;
else
odd++;
left++;
}
System.out.println ("There are: "+ zero + " zeros.");
System.out.println ("There are: "+ even + " even numbers.");
System.out.println ("There are: "+ odd + " odd numbers.");
}
}
How do you stop a conditional loop from running. For example if I write an if statement that accepts values from 0 to 100. How do stop the program if a user enters a number less then 0 or above 100.
import java.util.Scanner;
public class TestScores {
public static void main(String[]args) {
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++) {
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100) {
try {
throw new InvalidTestScore();
}
catch (InvalidTestScore e) {
e.printStackTrace();
}
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
You use the
break;
keyword. This breaks out of a loop.
You may want to use break
for(int i=0; i<100; i++)
{
if(user entered invalid value)
break; // breaks out of the for loop
}
Here's a hint, since this looks like homework to me: you can either use the break keyword, or use this condition:
if (grade[index] < 0 || grade[index]> 100)
{
// invalid grade...
}
as part of the loop condition.