Seeing as this is for a university assignment, I'm not sure how much detail I can give.
However I'll share what I believe I can.
In my main method I have this code;
System.out.println ("Please enter a year?");
int yearMenu = scan.nextInt();
System.out.println ("Please enter number of questions?");
int questionMenu = scan.nextInt();
confirmSessionDetails(yearMenu, questionMenu);
and this is my private static boolean 'confirmSessionDetails'
private static boolean confirmSessionDetails(int year, int questions)
{
String yearName = " ";
switch (year) {
case 1: yearName = "Year 1"; break;
case 2: yearName = "Year 2"; break;
default: yearName = "error"; break;
}
String questionNumber = " ";
switch (questions) {
case 1: questionNumber = "10"; break;
case 2: questionNumber = "20"; break;
default: questionNumber = "error"; break;
}
System.out.print ("You are a " + yearName + " student and want to do " + questionNumber + " questions. Is this correct (Y/N)?");
correctDetail = scan.next();
if (correctDetail.equalsIgnoreCase ("y"))
{
return true;
}
else
{
return false;
}
So what I want to know is how to get the return value and use it in my main method.
If return value is true it should move on to 'private static void displayQuestions()'
and if the return value is false it should loop back to asking the year and number of questions.
try something like this:
bool myVariable = confirmSessionDetails(yearMenu, questionMenu);
That will assign the returned value of the function confirmSessionDetails(yearMenu, questionMenu) and then you can use myVariable later on in your code.
I would do like :
Main
int yearMenu, questionMenu;
do{
System.out.println ("Please enter a year?");
yearMenu = scan.nextInt();
System.out.println ("Please enter number of questions?");
questionMenu = scan.nextInt();
} while (confirmSessionDetails(yearMenu, questionMenu);
displayQuestions();
Hope it helps.
Related
All right, so I have this program based where I want to print a receipt from a dentists office. As it is right now, you enter a number and the cost will print accordingly. However, I would like to able to enter multiple numbers in the program and when I type "-1" I want the program to stop and print the total cost. Take a look:
import java.util.Scanner;
public class DentistReception{
public static void main(String[] args) {
double cost = 0;
int treatment = 0;
final double checkUp = 60.00;
final double cleaning = 30.00;
final double cavity = 150.00;
Scanner input = new Scanner(System.in);
System.out.println("What service(s) will be done?: ");
System.out.println("Checkup: 1");
System.out.println("Cleaning: 2");
System.out.println("Cavity: 3");
System.out.println("Exit: -1");
treatment = input.nextInt();
{
if (treatment == 1) {
cost = cost + checkUp;
}
else {
if (treatment == 2) {
cost = cost + cleaning;
}
else {
if (treatment == 3) {
cost = cost + cavity;
}
else {
while (treatment < 0) break;
}
}
}
}
System.out.println("Total cost it:"+cost);
}
}
I want it to loop until i enter "-1", but the break doesn't seem like it wants to. Whenever I put the while or break somewhere else I get the message "break without loop" or something like that.
Use while and capture the option with a boolean variable
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
double cost = 0;
int treatment = 0;
final double checkUp = 60.00;
final double cleaning = 30.00;
final double cavity = 150.00;
boolean repeat = true;
while (repeat) {
Scanner input = new Scanner(System.in);
System.out.println("What service(s) will be done?: ");
System.out.println("Checkup: 1");
System.out.println("Cleaning: 2");
System.out.println("Cavity: 3");
System.out.println("Exit: -1");
treatment = input.nextInt();
input.nextLine();
switch (treatment) {
case 1:
cost = cost + checkUp;
break;
case 2:
cost = cost + cleaning;
break;
case 3:
cost = cost + cavity;
break;
default:
System.out.println("do you want to break out the loop?");
String ans = input.nextLine();
if (ans.equals("y")){
System.out.println("exiting...");
repeat = false;
}
break;
}
// if (treatment == 1) {
// cost = cost + checkUp;
// } else {
// if (treatment == 2) {
// cost = cost + cleaning;
// } else {
// if (treatment == 3) {
// cost = cost + cavity;
// } else {
// while (treatment < 0)
// break;
// }
// }
// }
}
System.out.println("Total cost it:" + cost);
}
}
Please forgive my noob-ness.
So, i figured out how to create two separate switch loops, in order to access two separate values. My trouble now, is that I don't know how to write a function that would allow me to concatenate the results of the two switch values.
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change',
setWeather);
document.getElementById('dance').addEventListener('change',
setDance);
function setWeather() {
var choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
}
}
function setDance() {
var art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
}
}
function result() {
weatherVal = weather.value;
danceVal = dance.value;
para.textContent = weatherVal + danceVal;
}
I tried to use the above code "function result()" to write the function to create the concatenation, but no success. I feel like the answer is right in front of me, but I'm just not quite sure what's going on.
You could make choice and art global variables and then use them in result like this:
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change', setWeather);
document.getElementById('dance').addEventListener('change', setDance);
var choice;
var art;
function setWeather() {
choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
break;
}
}
function setDance() {
art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
break;
}
}
function result() {
para.textContent = choice + art;
}
SORRY ABOUT FORMATTING. i am trying to determine if the grade is a passing, failing, or invalid grade. however i can't figure out how to catch the error.
EDIT: 70-100 OR "s" or "S" = pass; 0-69 OR u or U = retake; everything else = invalid.
This is my code:
import java.util.*;
public class Demo
{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
String total="";
System.out.println("enter grade");
total = kb.nextLine();
System.out.println(evaluateGrade(total));
}
public static String evaluateGrade(String expr)
{
String result ="";
boolean invalid = false;
int grade = Integer.parseInt(expr);
try{
if((grade <100 && grade >=70) || (expr.equalsIgnoreCase("s"))
{
result ="pass";
}
else if((grade <70 && grade >0)|| expr.equalsIgnoreCase("u"))
{
result ="retake";
}
else
{result="invalid";
}
} catch (Exception e)
{
}
return result;
}
}
This is my code:
import java.util.*;
class Demo{
public static void main(String [] args){
Scanner kb = new Scanner(System.in);
System.out.println("enter grade");
System.out.println(evaluateGrade(kb.next()));
kb.close(); // You need to ".close" your stuff
}
public static String evaluateGrade(String expr){
String result ="";
// boolean invalid = false; <--- This is not necessary
if(expr.equalsIgnoreCase("s")){
return "pass";
}
if(expr.equalsIgnoreCase("u")){
return "retake";
}
try{ // Try to get a Integer on "grade"
Integer grade = Integer.valueOf(expr);
if( (grade <= 100 && grade >=70)){ // 70 <= grade <= 100, and you forgot the ')'
result ="pass";
}
else if((grade <70 && grade >=0)){ // 0 <= grade < 70
result ="retake";
}
else{
result="invalid";
}
}
catch(NumberFormatException e){ // If "grade" is not a number, then you have this line
System.err.println("Your grade must be a NUMBER between 0 and 100.");
return "invalid"; // Return something to keep going with your code
}
return result;
}
}
If you're not understanding what is happening with your code, write it down on the paper.
Have a good day!
Ok, thanks, I have figured out the exit loop.
Now my problem is that I'm trying to test the int newScore to ensure its value is between 1 and 100. The loop halfway works. If I enter a value outside the parameters it loops and asks for it again. However, when I enter a value within the parameters it's not breaking the loop and continuing to the next part of the program (either asking for the next test score, or calculating the average if there are no more scores) This is the code I updated to try this loop:
do {
while (scoreValid) {
while (tv) {
try {
System.out.println("Please enter test score # " + counter);
newScore = Integer.parseInt(scan.nextLine());
if (newScore >= 1 && newScore <= 100) {
scoreValid = true;
tv = false;
counter++;
totalScore = totalScore + newScore;
break;
} else {
System.out.println("Sorry, you must enter a number between 1 and 100.");
tv = true;
continue;
}
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
}
} while (counter <= numberTests);
Here is the original code....
/**
* This app will average test scores and tell you what letter grade you received.
*
* #jordan.hawkes
* #1.0
*/
import java.util.Scanner;
public class TestScoreCalculator {
public static void main(String[] args) {
String first; // First Name entered by user
String last; // Last Name entered by user
String newTestAnswer; // answer for entering another test score
String redoAnswer; // answer to rerun program
int avg; // Average test score
int totalScore = 0; // Total Running Test Score
int newScore; // Test Score Entered by User
int counter = 1; // Number of Scores Entered
int testNumber; // Test # counter
int numberTests = 0; // Number of Tests entered by user
boolean scoreValid = false; // boolean to validate score
boolean newTest = false; // boolean to validate entering another test
boolean redo = false; // boolean to rerun program
boolean numberTestsValid = false; // boolean to validate number of tests
boolean test = false; // test boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
System.out.print("Please enter your first name: ");
first = scan.nextLine();
System.out.print("Hello, " + first + ", please enter your last name: ");
last = scan.nextLine();
while (redo = true) {
while (numberTestsValid = true) {
try {
System.out.println("Thanks, " + first + ", how many test scores would you like to enter? ");
numberTests = Integer.parseInt(scan.nextLine());
numberTestsValid = true;
break;
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
do {
while (scoreValid = true) {
try {
System.out.println("Great, please enter test score # " + counter);
newScore = Integer.parseInt(scan.nextLine());
scoreValid = true;
counter++;
totalScore = totalScore + newScore;
break;
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
} while (counter <= numberTests);
testNumber = counter - 1;
avg = (totalScore / testNumber);
switch (avg / 10) {
case 10:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an A+!");
break;
case 9:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an A!");
break;
case 8:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a B!");
break;
case 7:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a C!");
break;
case 6:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a D!");
break;
default:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an F!");
}
while (test = true) {
System.out.println("type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
test = false;
totalScore = 0;
counter = 1;
redo = true;
break;
} else if (redoAnswer.equals("q")) {
test = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that. Please type r to restart or q to quit");
continue;
}
}
}
} //end main
} //end class
Classic bug:
while (redo = true)
assigns true to redo and is always true, it doesn't test it.
change it to either
while (redo == true)
or far better:
while (redo)
Same goes for other loop conditions.
I have 4 objects in my Array. lastName, firstName, fighterKills, motherShipKills. What I want to is be able to sort this by one of these objects. (Alphabetically or numerically). I converted the Array into a String. Should I sort before or after a convert it.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class SpaceInvaders {
public SpaceInvaders() {
addData(lastName, firstName, fighterKills, motherShipKills);
sortBy();
print();
}
ArrayList<Player> players = new ArrayList<Player>();
String toString="";
Scanner scan = new Scanner(System.in);
int x = 10;
String lastName;
String firstName;
int fighterKills;
int motherShipKills;
public void addData (String lastName, String firstName, int figherKills, int motherShipKills) {
int x = 10;
System.out.println("Welcome to Space Invaders!");
for(int i = 0; i < x; i++) {
System.out.println("Please Enter Last Name or the name of your text file or if you are done entering please enter 'done': ");
lastName = scan.nextLine();
if(lastName.equals("done")) {
for (Player player : players) {
System.out.println(players);
break;
}
break;
}
else {
System.out.println("Please Enter First Name: ");
firstName = scan.nextLine();
System.out.println("Please Enter Fighter Kills: ");
fighterKills = scan.nextInt();
System.out.println("Please Enter Mothership Kills: ");
motherShipKills = scan.nextInt();
Player player = new Player(lastName, firstName, fighterKills, motherShipKills);
players.add(player);
String line;
System.out.println(players);
scan.nextLine();
}
}
}
public void sortBy () {
System.out.println("How would you like this sorted? 'Last Name'-1, 'First Name'-2, 'Fighter Kills'-3 or 'Mothership Kills'-4? ");
System.out.println("Please enter the number corresponding to the way you would like this sorted: ");
int sortBy = scan.nextInt();
if (sortBy == 1) {
System.out.println("Finished");
}
if (sortBy == 2 ){
System.out.println("Yee Buddy");
}
if (sortBy == 3) {
bestFighter();
}
if (sortBy == 4) {
bestMotherShip();
}
}
public String toString () {
for (Player play : players) {
toString += play.toString()+ "\n";
}
return toString;
}
public void print() {
}
public String bestFighter() {
}
public String bestMotherShip() {
String bestMotherShip = "Working";
System.out.println("Working");
return bestMotherShip;
}
public static void main(String[] args) {
SpaceInvaders tp = new SpaceInvaders();
System.out.println(" LAST NAME " + "\t" + " FIRST NAME " + "\t" + " FIGHTER KILLS " + "\t" + " MOTHERSHIP KILLS ");
System.out.println(" -------------------------------------------------------------------");
System.out.println( tp.toString());
}
}
So I would input "Smith", Bob", "2", 24" and then "Joe", "Shmo", "3", "15". And it would print
Smith Bob 2 24
Shmo Joe 3 15
If I wanted it sorted by the fighterkills it would change to
Shmo Joe 3 15
Smith Bob 2 24