Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am still a bit new to Java and I could use some help with this code please, so far i wrote the methods and what each methods should do but I honestly have no idea how to do the overloading effect and make it work so I would appreciate a simple explanation.
import java.util.Scanner;
public class Assignment3 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
myMethod();
}
public static void myMethod(){
System.out.println("Welcome to Java 1 ");
}
public static void myMethod(String msg, int counter){
System.out.println("Enter your custom messege please: ");
msg = input.nextLine();
System.out.println("Please enter how many times do you wish to print the messsege: ");
counter = input.nextInt();
for (int i = 0; i <= counter; i++){
System.out.println(msg);
}
}
public static void myMethod(int lowerLimit, int upperLimit){
System.out.println("Please enter a lowerlimit: ");
lowerLimit = input.nextInt();
System.out.println("Please enter an upperlimit: ");
upperLimit = input.nextInt();
System.out.println("Press 1 for ascending order: ");
System.out.println("Press 2 for descending order: ");
System.out.println("Make your selection");
int user1 = input.nextInt();
System.out.println("How frequent do you wish the messege to be printed");
int interval = input.nextInt();
switch(user1){
case 1:
for(int counter = lowerLimit; counter <= upperLimit; counter += interval){
System.out.println(counter);
}
break;
case 2:
for(int counter = upperLimit; counter <= lowerLimit; counter -= interval){
System.out.println(counter);
}
break;
default :
System.out.println("Something went wrong !!!");
}
}
public static void myMethod(double number1, double number2){
number1 = (Math.random() * 100);
number2 = (Math.random() * 100);
double product = (number1 * number2);
System.out.println("The product of " + number1 + " and " + number2 + " is " + product);
}
]
Your myMethod method is already overloaded. An overloaded method is just a method that can accept two or more different sets of parameters. (see https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html)
For example :
public void foo(int a) {
System.out.println("Printing out the int " + a);
}
public void foo(double a) {
System.out.println("Printing out the double " + a);
}
Foo has two possible parameter sets, one that accepts an int and one that accepts a double. Now, if you do this :
int a = 10;
double b = 10.5;
foo(a);
foo(b);
It'll return :
Printing out the int 10
Printing out the double 10.5
In response to your comment:
You just need to call the two other "myMethod" in your main, with their respective signatures:
public static void main(String[] args) {
// Call without argument
myMethod();
// Call with String and integer
myMethod("test", 42);
// Call with Integer and Integer
myMethod(42, 666);
}
The right ones will be called then. Does this answer your question ?
Above post has your answer, Your myMethod method is already overloaded but Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different.
You have your method which accepts different parameters with different datatypes
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner (System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake,BMR);
//this is what you actually ate
actualCalories(actualIntake,BMR);
//gym with protein
gym (30,40,50,100, actualIntake);
}
//testing method
testingMeth(actualIntake);
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR){
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0 ){
calorieDifference = Math.abs (BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0){
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories (int actualIntake, int BMR ) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR ) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR ) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin." );
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym (int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50 ) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50 ) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth (int actualIntake) {
System.out.println(actualIntake);
}
}
//Take calories in then calculate BMR and compare, return value
So I am currently learning java, just learning and making random calorie deficit and BMR program. I created a new method called:
public static int testingMeth(actualIntake) {
System.out.println(actualIntake);
}
The issue is when i try to call the method after the gym method, it creates an error.
gym (30,40,50,100, actualIntake);
}
testingMeth(actualIntake);
If i was to delete the gym method from the main method, all my other methods has errors. I do not necessarily need a solution for this program but rather why am i receiving these errors? Just want to learn and improve! Thanks.
In other words, I can call the testingMeth before the Gym method and it works fine, but why not after the gym method? and if i get rid of the gym method, multiple errors occur amongst the other methods within the program?
If you see below code, i am able to run both method in any sequence and it's working fine as well.
You need to go through with basics of method declaration and method call.
It will help you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner(System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake, BMR);
//this is what you actually ate
testingMeth(actualIntake);
actualCalories(actualIntake, BMR);
//gym with protein
gym(30, 40, 50, 100, actualIntake);
}
//testing method
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR) {
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0) {
calorieDifference = Math.abs(BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0) {
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories(int actualIntake, int BMR) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin.");
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym(int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth(int actualIntake) {
System.out.println(actualIntake);
}
}
You need to understand for every opening braces of class/method/switch-case/or condition must have closing braces.
In your case you are try to call some method after closing braces of class, so those elements are not part of your class and that's why it's throwing an error.
I was wondering when I tried to print the value of recursion in main, the answer was:
Enter the number: 1
2The result is:
How to make the number 2 to the front like,
The result is: 2
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
To call the method:
System.out.printf("The result is: ", multiplication(a));
first the arguments must be evaluated, so multiplication(a) is executed before System.out.printf("The result is: ", multiplication(a)). Since multiplication(a) prints something, that printing takes place before "The result is:" is printed.
You should change multiplication(a) to simply return the result without printing it. Then use System.out.println("The result is: " + multiplication(a)) to print the result.
Note the you have to change the value returned by multiplication(a), since currently you return a, which is not the value printed by that method.
You have 2 issues in your code.
First is you are printing the value of 'multiply' in your static method :
public static int multiplication(int a){
System.out.print(multiply);
That is a reason why it is printing 2 before the statement :
2The result is:
2nd issue is you are calling the method multiplication in the print statement :
System.out.printf("The result is: ", multiplication(a));
That is not how to print the result by calling the method.
I have taken your example and run the below code. You can check this code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
Below are the outputs on different options :
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2
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 in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My program should ask the user for the name, the price as well as the amount of what he wants, until he presses "x". At this point the program should print the receipt.
How can I save all the user inputs without knowing how many items he wishes to buy?
I am using three classes. I do not know how to give the names, amounts, prices from the Main-class to the class Eintrag.
How do I call the list from the Kassenzettel class in the main for me to print?
Also, I override the to String method, for my receipt to "supermarket-like", will this formatting be applied in the main class?
here is my main -class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like? ");
String produkt = scanner.nextLine();
System.out.println("How many pieces do you want?");
int anzahl = scanner.nextInt();
System.out.println("How much does " + produkt + "cost?");
double preis = scanner.nextDouble();
//Im not even sure if that should be there
Kassenzettel list =new Kassenzettel();
Eintrag carrots = new Eintrag("carrots", 5, 0.40);
Kassenzettel.add(carrots);
System.out.println("__________________________________");
System.out.println(" IHRE RECHNUNG ");
System.out.println("__________________________________");
}
}
My Eintrag-class:
public class Eintrag {
private String produkt;
private double preis;
private int anzahl;
public Eintrag(String produkt, int anzahl, double preis) {
this.anzahl=anzahl;
this.produkt=produkt;
this.preis=preis;
}
public int getAnzahl(){
return this.anzahl;
}
public double getPreis(){
return this.preis * this.anzahl;
}
public String getProdukt() {
return this.produkt;
}
public void setAnzahl(int anzahl) {
this.anzahl = anzahl;
}
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",produkt , anzahl, preis
+ "%30.2f EUR", anzahl * preis));
}
}
My Kassenzettel class, which should consist of a list of Eintrag objects
import java.util.ArrayList;
public class Kassenzettel {
private static ArrayList<Eintrag> kassenZettel;
private double summe;
// Constructs a new empty grocery list.
public static void add(Eintrag item) {
kassenZettel.add(item);
}
#Override
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",kassenZettel
+ "%30.2f EUR"
+ "SUMME", summe));
}
}
Not sure, if i got, what you want, but you can use something like this:
change the toString method of Kassenzettel to:
double sum = 0;
String ret = "";
for(int i = 0; i< kassenZettel.size(); i++){
ret += kassenZettel.get(i).toString()+"\r\n";
sum += kassenZettel.get(i).getPreis();
}
ret += "\r\nSumme: "+sum;
The next point, you have to make a loop for user input:
Scanner scanner = new Scanner(System.in);
//create an instance of kassenzettel to add your produkts to
Kassenzettel list =new Kassenzettel();
//set variable to check if read or not (not needed if using break!)
boolean readOn = true;
//loop for reading until user inputs x or X
while(readOn){
System.out.println("What would you like? ");
String produkt = scanner.nextLine();
//check if produkt name is X or x => exit the loop
if(produkt.equalsIgnoreCase("x")){
readOn = false;
break;
}
System.out.println("How many pieces do you want?");
int anzahl = scanner.nextInt();
System.out.println("How much does " + produkt + "cost?");
double preis = scanner.nextDouble();
//add a new item to kassenzettel
list.add(new Eintrag(produkt, anzahl, preis));
}
//print the output of kassenzettel
System.out.println(list.toString());
EDIT:
and remove:
//Im not even sure if that should be there
Kassenzettel list =new Kassenzettel();
Eintrag carrots = new Eintrag("carrots", 5, 0.40);
Kassenzettel.add(carrots);
Working code:
http://pastebin.com/3acgm5St