java using returned values from methods - java

My student grade classifier needs to use the returned values, and I have tried but the input is prompted for three times. I'm sure this is because I'm calling the method getStudentMark() to use the retrieved value from that method.
Code:
public static int getStudentMark()
{
Scanner in = new Scanner(System.in);
System.out.println("Exam Mark :> ");
int mark = in.nextInt();
return mark;
}
public static String getStudentFinalGrade()
{
int studentGradeMark = getStudentMark();
String studentGrade = "";
int studentGradeMark = getStudentMark();
if (studentGradeMark >= 90) {
return "A";
} else if (studentGradeMark >= 80) {
return "B";
} else if (studentGradeMark >= 70) {
return "C";
} else if (studentGradeMark >= 65) {
return "D";
}
return "F";
return studentGrade;
}
public static void printGrade()
{
System.out.println("Your Grade is" + getStudentFinalGrade());
}
Then calling these in the main method (which I cannot change):
public static void main(String[] args) {
getStudentMark();
getStudentFinalGrade();
printGrade();
}
Where am I going wrong when assigning the int?
It keeps asking for an input 3 times. Then works on the third attempt

to get an input grade. Just read nextLine, use a regular expression to see it's a number and the use Integer.parseint(String grade) to get the final grade.

Related

I'm trying to create a looping validation method that tests data type and range

I'm new to java and I'm tinkering with my code and decided to create an input validation method, my problem is how am I going to loop the input through the validations.
First I decided to take the input as string to do a try/catch with a double, no problem with that, now I need to test the input if it's in the range of 0-100. Of course I wanted to check if the user will type in a double in the "range check". What I wrote somewhat worked but when the input passed the data type validation but not the range check, it will still return the first double, whatever I typed next.
public static double check(String n){
boolean done = false;
double i=0.0;
Scanner beep = new Scanner(System.in);
while (!done) {
try {
i = Double.parseDouble(n);
done = true;
} catch (Exception e) {
System.out.print("Please input a valid grade (0-100): ");
n = beep.nextLine();
}
}
double b = rangetest(i);
return b;
}
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
public static void main(String[] args) {
Scanner beep = new Scanner(System.in);
double ave = 0.0;
int rounded;
for (int i = 1; i <= 5; i++)
{
System.out.print("Input grade number " + i + " : ");
ave += rangetest(check(beep.next()));
}
ave /= 5;
rounded = (int)Math.round(ave);
}
Is there any easier methods or workarounds? Or am I doing it all wrong? Cheers!
Beware of Scanner#next, this can leave a dangling new line character in the buffer which can mess with your workflows, however, the core issue is with your rangetest
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
Here, if the value is not within the specified range, you're calling check again, but you're ignoring the result, so you end up returning the original value of n
It would seem that instead, you want to do...
n = rangetest(check(beep.next()))
within the if block.
You could accomplish something similar using do-while loops, for example...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double value = getDoubleWithinRange(scanner, "Make me an offer ([X] to exit): ", "That's not a reasonable offer", "X", 0, 100, "Value is not within a valid range (0-100)");
if (value != null) {
System.out.println("You mad an offer of " + value);
}
}
public static Double getDoubleWithinRange(Scanner input, String prompt, String errorMessage, String exitValue, double min, double max, String rangeErrorMessage) {
boolean done = false;
Double value = null;
do {
value = getDouble(input, prompt, errorMessage, exitValue);
if (value != null) {
if (isWithinRange(value, 0, 100)) {
done = true;
} else {
beep();
System.out.println(rangeErrorMessage);
}
} else {
done = true;
}
} while (!done);
return value;
}
public static void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
public static boolean isWithinRange(double value, double min, double max) {
return value >= min && value <= max;
}
public static Double getDouble(Scanner input, String prompt, String errorMessage, String exitValue) {
Double value = null;
boolean exit = false;
do {
System.out.print(prompt);
String nextLine = input.nextLine();
Scanner parser = new Scanner(nextLine);
if (parser.hasNextDouble()) {
value = parser.nextDouble();
} else if (nextLine.equals(exitValue)) {
exit = true;
} else {
beep();
System.out.println(errorMessage);
}
} while (!(value != null || exit));
return value;
}
}
nb: I have a exit condition available, you don't need it, but it's nice as a demonstration
I fashioned myself a function from #MadProgrammer's code (Thanks man!), this somehow works a wee bit simpler.
public static double getValue() {
Scanner beep = new Scanner(System.in);
boolean flag = true;
double value=0.0;
while(flag==true){
if(beep.hasNextDouble()){
value = beep.nextDouble();
if(value>=0&&value<=100){
flag=false;
}
else{
System.out.print("Invalid input, 0-100 only: ");
beep.nextLine();
}
}
else{
System.out.print("That's not a numerical value, try again: ");
beep.nextLine();
}
}
return value;
}
Feel free to comment, make a correction and/or suggest anything that would make this better.

Confusion about how to process lines in a text file as they are read

So I was given the following GradedActivity class:
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
if (s < 0)
score = 0.0;
else if (s > 100)
score = 100.0;
else
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} }
and I was tasked with generating a constructor that accepts values for points Obtaned and pointsTotal as arguments, initializes them, and sets the corresponding score (points obtained divided by points total), accessors and mutators for pointsobtained and total.
So here is what I came up with:
public class ProgrammingAssignment extends GradedActivity
{
public int pointsObtained;
public int pointsTotal;
public ProgrammingAssignment(int p, int t)
{
pointsObtained = p;
pointsTotal = t;
}
public int getPointsObtained()
{
return pointsObtained;
}
public int getPointsTotal()
{
return pointsTotal;
}
public double getScore()
{
return pointsObtained / pointsTotal;
}
public void setPointsObtained(int p)
{
pointsObtained = p;
}
public void setPointsTotal(int t)
{
pointsTotal = t;
}
}
Everything compiles without error, but getScore isn't computing obtained/total (it comes back 0) in my test class:
public class PADemo
{
public static void main(String[] args)
{
ProgrammingAssignment p1 = new ProgrammingAssignment(28,30);
GradedActivity p2 = new ProgrammingAssignment(0,30);
System.out.println (p1.getPointsObtained());
System.out.println (p1.getPointsTotal());
System.out.println (p1.getScore());
System.out.println (p1.getGrade());
System.out.println (p2.getScore());
System.out.println (p2.getGrade());
p1.setPointsObtained(25);
p1.setPointsTotal(40);
System.out.println (p1.getScore());
System.out.println (p1.getGrade() == 'F');
}
}
How do I obtain the score (points obtained/points total) with getScore()
Test class returns:
28
30
0.0
F
0.0
F
0.0
true
Cars waiting: [a A123TR, a Z23YTU, a R23EWQ, a ERW345, a B12GFT...
Does that look correct? Why would you have the "a " at the beginning? That is not part of the car license. The "a " and "d " need to be removed BEFORE you add the license to the garage or queue.
creates a stack for cars in a garage (Max of 7)
a queue for cars waiting (max of 5)
Your basic logic appears wrong (to me).
When you get an "a" you do one of two things:
if there are less than 7 cars in the garage you add the car to the garage.
If there are 7, then if then are less the 5 cars in the queue, you add the car to the "queue".
When you get a "d" you:
first remove the car from the "garagee",
then you check the "queue". If there are cars in the "queue" then you move the car from the "queue" to the "garage".
So the logic might be structure something like:
while (...)
{
...
String[] data = line.split(" ");
if (data[0].equals("a"))
processArrival( data[1] );
else if (data[0].equals("d"))
processDeparture( data[1] );
}
I used the String.split(...) method which was suggested in your last question because it is a better test then to test the whole String for a specific character and your two pieces of data are separated into the array ready for processing. The data will now be split into two pieces of data: a) function
b) license
I used separate methods because the code is easier to read and logic for each function is contained in individual methods.

How does one pass parameters between methods and correctly call the method using Java?

The program should do the following:
Write a method called getheartRate that takes no parameters and returns an int (heartRate).
This method prompts the user for the patient's heart rate, reads
their input from the command line, and returns this value.
Write a method called checkHeartRate that takes an int parameter (the heart rate) and returns
a String (result). If the heart rate is above 100, return the value "High". If the heart rate is below
60, return the value "Low". Otherwise return "Normal".
Write a method called printHRResult that takes a String parameter, which is the result
from the method checkHeartRate. Print this value to the command line.
Call all three methods from the main method using appropriate parameter passing.
So far I have:
public class UnitSixInClassFall2018 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
UnitSixInClassFall2018 u = new UnitSixInClassFall2018();
u.getHeartRate();
System.out.println();
Scanner scan = new Scanner(System.in);
u.checkHeartRate(0);
// END MAIN
}
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
return 0;
}
public void checkHeartRate(int heartRate){
if (heartRate > 100) {
String result = "High";
}
else if (heartRate < 60) {
String result = "Low";
}
else {
String result = "Normal";
}
}
public String printHRResults(String result) {
System.out.print("Your hear rate is " + result + ".");
return result;
}
}
When this is run, all that is output is "Please enter your heart rate: ". Once I enter an integer, the program ends. What is being done incorrectly?
You should change this method to return the heart rate like this:
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
// Also add this
scan.close();
return heartRate;
}
And change this method to return the result:
public String checkHeartRate(int heartRate){
if (heartRate > 100) {
return "High";
}
else if (heartRate < 60) {
return "Low";
}
else {
return "Normal";
}
}
Then in your main method:
// get the heart rate
int heartRate = u.getHeartRate();
// Call the checkHeartRate method
String result = checkHeartRate(heartRate);
// call the printHRResults
printHRResults(result);
That should solve your problem.
First of all, you are creating two Scanner objects with the same input type (System.in), which isn't recommended. Instead, just make one Scanner object and use it everywhere in your program. This post has some good info.
An improved version of your code with an improved use of the Scanner object is as follows:
public UnitSixInClassFall2018 {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
NewMain u = new NewMain();
int heartRate = u.getHeartRate();
System.out.println();
String result = u.checkHeartRate(heartRate);
u.printHRResults(result);
scan.close(); // Close the scanner once you are completely done using it
}
public int getHeartRate() {
System.out.print("Please enter your heart rate: ");
return scan.nextInt(); // Return the input of the user
}
public String checkHeartRate(int heartRate) {
String result = ""; // Initialize some default value
if (heartRate > 100) {
result = "High";
}
else if (heartRate < 60) {
result = "Low";
}
else {
result = "Normal";
}
return result; // Return the result calculated from the if-statements
}
public void printHRResults(String result) {
System.out.print("Your heart rate is " + result + ".");
// Originally this method returned a string but that seems unnecessary
}
}

Returning/Passing Variables in Java

I am a beginning programmer and we were assigned to implement methods into a code. I had this grade average code working fine, but once I broke it up into methods, I could not get the return functions to work. I have tried moving brackets and rearranging the code but to no avail. I believe it may have to do with the scope of my variables... Thanks in advance :)
package milsteadgrades;
import java.util.Scanner;
public class MilsteadGrades {
public static void main(String[] args)
{
//Call methods to execute program.
displayInfo();
double numOfgrades = getInput();
double average = getAverage(numOfgrades);
char letgrade = determineLetterGrade(average);
displayGrades(average, letgrade);
}
public static void displayInfo()
{
System.out.println("Mallory Milstead");
System.out.println("This program will prompt the user for a number of
grades"
+ " and each grade. Then the program calculates and displays the average and
letter"+" grade.");
}
public static double getInput()
{
//Prompt user to enter number of grades and assign that number to
numOfgrades.
System.out.print("How many grades would you like to average? ");
Scanner keyboard = new Scanner(System.in);
double numOfgrades = keyboard.nextDouble();
return numOfgrades;
}
public static double getAverage(numOfgrades)
{
//Prompt the user to enter grades.
System.out.println("Enter exam scores : ");
Scanner keyboard = new Scanner(System.in);
double total = 0;
for (double i = 0; i < numOfgrades; i++) {
double grade = keyboard.nextDouble();
total+=grade;}
double average = total/numOfgrades;
return average;
}
public static char determineLetterGrade(average)
{ double testscore = average;
char letgrade;
if (testscore >= 90)
{
letgrade = 'A';
} else if (testscore >= 80)
{
letgrade = 'B';
} else if (testscore >= 70)
{
letgrade = 'C';
} else if (testscore >= 60)
{
letgrade = 'D';
} else
{
letgrade = 'F';
}
return letgrade;
}
public static void displayGrades(average, letgrade)
{
System.out.println("The average of the grades is "+average+ " and the
letter grade"+ " is " + letgrade+".");}
}
Beginning with the line -public static double getAverage(numOfgrades)-, I continuously get "cannot find symbol" error message. None of my variables is being recognized.
You need to declare the type of the argument of getAverage. Like
public static double getAverage(double numOfgrades)
Similiarly for your other methods(not modules). Have a read of this or this for tips.

Basic Java questions Scanning

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Categories

Resources