Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}
Related
New to Java. The task is to Create a MathQuiz application that asks the user whether they would like a simple or difficult math quiz and the number of questions they would like to answer. The application then displays the questions, one at a time,prompting the user for the answer and confirming whether or not the answer is correct. The MathQuiz application should include separate methods for the simple and difficult math quiz.The simple() method should display addition problems. The difficult() method should display multiplication problems. Random numbers should be generated for the quiz questions. This is what I have so far:
import java.util.Scanner;
public class MathQuiz {
public static double simple() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberAdd = randomNumber1 + randomNumber2;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " + " + randomNumber2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == randomNumber1 + randomNumber2) {
System.out.println("Correct!");
}else {
System.out.println("Wrong. The correct answer is " + randomNumberAdd);
}
}
public static double difficult() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberMul = randomNumber1 * randomNumber2;
int correct = 0;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == randomNumber1 * randomNumber2) {
System.out.println("Correct!");
}else{
System.out.println("Wrong. The correct answer is " + randomNumberMul);
}
}
//user options
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
System.out.println("There are two levels available:");
System.out.println("1. Simple");
System.out.println("2. Difficult");
System.out.print("Enter your choice: ");
choice = input.nextInt();
if (choice == 1) {
simple();
} else if (choice == 2) {
difficult();
}
input.close();
}
}
public static double simple() {}
public -> It specifies the access level of this function.
static -> It means this function is a behavior of your class and not specific to any instance of this class.
double -> It's what your function returns, a double typed value here, as an output at end of execution.
simple()-> It's your function name
In both of your functions simple() and difficult() you are not returning any value as output. So you have to change it to void.
Change your method simple() and difficult() return type from double to void and the error should go away
Change the return type of simple() and double() method to void, i.e.
public static void simple() and
public static void difficult()
The return type of these methods is currently double, so it is expected to return a double value. If they don't return a double value, the compiler will give you an error. So, if you don't plan to return a value in your methods, change the return type to void.
Removing the return type of double from your method's signature and setting it to void, the error should go away.
public static void simple() {
// your code
}
public static void difficult() {
// your code
}
I'm currently working on a GPA calculator for a class of mine. I keep getting an error that has to do with the division I'm trying to do on the GPA calculation and am having trouble with the syntax for sub-strings and how to use them correctly. Below is the code I have so far. If you see anything I can fix that's not to complicated I'm open to all suggestions.
import java.util.Scanner;
public class GPA
{
public static void main(String[] mydata)
{
Scanner sc = new Scanner(System.in);
String choice = "";
String cnum;
String grade;
double points;
double gpa = 0;
int count = 0;
String credit= "", totalCredit = "";
while (!choice.equalsIgnoreCase("Q"))
{
cnum = (mydata[0]);
grade = (mydata[1]);
if (grade.equalsIgnoreCase("A")) {points = 4.0;}
else if (grade.equalsIgnoreCase("B")) {points = 3.0;}
else if (grade.equalsIgnoreCase("C")) {points = 2.0;}
else if (grade.equalsIgnoreCase("D")) {points = 1.0;}
else if (grade.equalsIgnoreCase("F")) {points = 0.0;}
credit = cnum.substring(3,4);
//System.out.println("credits = " + totalCredit);
System.out.println("GPA = " points/Double.parseDouble(credit));
System.out.print("Enter next course number and grade or ‘Q’ to quit: ");
System.out.println();
choice = sc.nextLine();
}
System.out.println("Bye!");
}
}
Not bad but there are a couple syntactical errors with your code:
The println argument needs to be concatenated with a +:
System.out.println("GPA = " + points / Double.parseDouble(credit));
The local variable, points, needs to be initialized since your if-else conditions are not exhaustive (ie: grade has a runtime range of A, B, C, D, or F but grade can technically be assigned to whatever is in mydata[1]). Either add an else condition or assign an initial value to points:
double points = 0.0;
Be sure to include + to concat the strings together :)
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
I believe you want to be concatenating here.
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
Instead of
System.out.println("GPA = " (points/Double.parseDouble(credit)));
And if you want
int theGpa = points/Double.parseDouble(credit));
System.out.println("GPA: " + theGpa);
While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}
This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}