How to store multiple variables in this code? [closed] - java

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 8 years ago.
Improve this question
I'm writing a program to find out if a number is even or odd and I have all of the code working, but I don't know how to write in other examples. Here is the code I have so far:
import static java.lang.System.*;
public class numberverify
{
public static boolean isOdd( int num)
{
return ((num % 2) == 1);
}
public static boolean isEven( int num)
{
return ((num % 2) == 0);
}
}
and the runner:
import static java.lang.System.*;
import java.util.Scanner;
public class numberverifyrunner
{
public static void main ( String[] args )
{
Scanner keyboard = new Scanner(in);
System.out.print("Enter an Integer :: ");
int num = keyboard.nextInt();
System.out.println( num + " is odd :: " + numberverify.isOdd(num));
System.out.println( num + " is even :: " + numberverify.isEven(num) + "\n");
//add in more test cases
}
}

Do this:
while(keyboard.hasNextInt())
{
int num = keyboard.nextInt();
System.out.println( num + " is odd :: " + numberverify.isOdd(num));
System.out.println( num + " is even :: " + numberverify.isEven(num) + "\n");
}
The program should quit if you put anything other than an integer in.

You could simplify this code somewhat (and make it easier to maintain) by only having a single method that performs the check. The second method can simply call the first one, for example:
public static boolean isOdd(int num) {
return ((num % 2) == 1);
}
public static boolean isEven(int num) {
return !isOdd(num);
}
For that matter, using a bitwise AND operation here is more efficient:
public status boolean isEven(int num) {
return (num & 1) == 0;
}

Related

Method not being called properly?! Calorie App [closed]

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.

What do I need to fix to get the code to compile? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Write a Java program with a recursive method that accepts a value i as input and computes the sum:
m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + ... + i/(2i + 1)
So far I have:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
if (i == 0) {
System.out.println(0);
}
else {
System.out.println(i / (2 * i + 1) + (main(i-1)));
}
}
}
The code isn't compiling. Please help!!
Ok I think I finally understand what you're trying to do! The problem is you're actually trying to build a string! The method is doing what it should, your return just isn't really doing what it should.
import java.util.Scanner;
public class Recursion
{
private static String result = null;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
System.out.println(recursion(i));
}
public static String recursion(int i)
{
if(i != 0)
{
if(result == null)
{
result = (i + "/" + (2 * i + 1));
recursion(i - 1);
}
else
{
result = result.concat(" + ").concat(i + "/" + (2 * i + 1));
recursion(i - 1);
}
}
return result;
}
}
Please let me know if this does what you want it to!
You shouldn't use recursion on the main function. Just create a second function that isn't the main and it should work:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
System.out.println(recursion(i));
}
public int recursion(int i){
if (i == 0) {
return 0;
}
else {
return (i / (2 * i + 1) + (recursion(i-1)));
}
}
}

Overloading methods in Java? [closed]

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

Using recursion to compute factorials without new variables [duplicate]

This question already has answers here:
Recursion vs For loops - Factorials, Java
(3 answers)
Closed 6 years ago.
I am trying to compute the entered factorial in the method factorialRecursive by using recursion, However I cannot declare any variables or objects in that method and thats what i am struggling with, my attempt is in the method already but doesn't work. This has to call itself in a While loop not a for loop.
class Factorial{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = input.nextInt();
} while (number < 0);
System.out.println(number + "! = " + factorialIterative(number) + " (iterative)");
System.out.println(number + "! = " + factorialRecursive(number) + " (recursive)");
}
private static int factorialIterative(int num) {
int result = 1;
while (num > 0) {
result = num*result;
num--;
}
return result;
}
private static int factorialRecursive(int num){
if (num==1 | num==0)
return 1;
return num*(num-1) * num;
}
}
Try this:
private static int factorialRecursive(int num) {
// Warning here use || instead of |
if (num==1 || num==0)
return 1;
return num * factorialRecursive(num - 1);
}
I can also be simplified like this:
private static int factorialRecursive(int num) {
return (num == 1 || num == 0) ? 1 : num * factorialRecursive(num - 1);
}
You don't need to declare any variables. Take advantage of the recurrence relation for factorials:
n! = n * (n - 1)!
Multiply num by the result of making a recursive call by passing num - 1. Return that product without storing it in a variable.
Recursivity means you need to call the method itself inside of the method
Example:
private static int factorialRecursive(int num){
if (num==1 | num==0)
return 1;
return num*factorialRecursive(num-1);
}
and since factorial will increase really high with low values, consider to use other data type than integers... otherwise it will only work until factorial(16) after that you will get invalid data by using ints...
private static long factorialRecursive(long num){
if (num==1 | num==0)
return 1;
return num*factorialRecursive(num-1);
}

having a variable in recursive method not redefine itself after each call

I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""

Categories

Resources