I get the numbers scanned in correctly, but the methods aren't working right. First one doesn't do anything and the second one goes into an infinite loop.
Method called is not performing correctly. I am not sure what to do.
import java.util.Scanner;
public class testSequence {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int enterNumber = scan.nextInt();
System.out.println("1 for Iteration, 2 for Recursion: ");
int type = scan.nextInt();
if (type == 1){
computeIteration(enterNumber);
} else if (type == 2){
computeRecursion(enterNumber);
}
}
public static int computeIteration(int enterNumber) {
int answer;
int multiplier = 1;
int count = 0;
int addend = 0;
if (enterNumber == 0) {
count++;
return enterNumber;
} else if (enterNumber == 1) {
count++;
return enterNumber;
} else {
for (int i = 0; i <= enterNumber; i++) {//need to adjust "i" for counter correction
enterNumber = (multiplier * 2) + addend;
addend = multiplier;
multiplier = enterNumber;
count += 1;
}//end for loop
answer = enterNumber;
}//end else
return answer;
}//end computeIteration
public static int computeRecursion(int n) {
int count = 0;
if (n == 0) {
count++;
return 0;
} else if (n == 1) {
count++;
return 1;
} else {
count++;
return computeRecursion(2 * (n - 1)) + computeRecursion(n - 2);
}
}//end computerRecursion()
}//end Sequence()
You're never printing the answer.
if (type == 1){
computeIteration(enterNumber);
} else if (type == 2){
computeRecursion(enterNumber);
}
Note how you're calling the functions, but you never do anything with the result.
You probably meant:
if (type == 1){
System.out.println(computeIteration(enterNumber));
} else if (type == 2){
System.out.println(computeRecursion(enterNumber));
}
Or, if you wanted to get fancy:
UnaryOperator<Integer> f =
type == 1 ?
computeIteration
: computeRecursion;
System.out.println( f.apply(enterNumber) ) ;
Just an addition since you asked. I'm using the ternary operator because I need to choose between 2 things. In a case like this, it's neater than a full if statement.
The UnaryOperator is a functional interface. Basically, using them, you can save a function inside a variable. This is useful where in cases like this, you want to choose between 2 functions whose signatures are the same (both of your functions take an int, and give back an int), and use the result.
I save one of your functions into f, then call it by writing f.apply(9) (apply "applies" the arguments to the function; calling it).
Note you shouldn't use functional interfaces just for kicks, as they can make code less clear. When used properly though, they can make code much simpler; especially when paired with anonymous functions.
Related
As an exercise I need to make a code that will give the amount of happy numbers* in a given range. As a test I need to insert the code in a program that checks 10 different outcomes, for every good outcome you get 4 points. I want the full 40 points and my teacher said that I need to change only a little bit in my code. So far I have this:
*A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. For instance, 13 is a happy number because 1^2 + 3^2 = 10 and 1^2 + 0^2 = 1
Important to know: When you end up with a 4, it is definitely not a happy number.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String st1 = scan.nextLine().trim();
String st2 = scan.nextLine().trim();
int min = Integer.parseInt(st1);
int max = Integer.parseInt(st2);
Set<Integer> happyNumbers = getHappyNumbers(min, max);
System.out.println(happyNumbers.size());
}
public static Set<Integer> getHappyNumbers(int min, int max) {
Set<Integer> out = new HashSet<>();
for (int i = min; i < max; i++) {
if (isHappy(i)) {
out.add(i);
}
}
return out;
}
private static boolean isHappy(int i) {
int sum = 0;
while (i != 0) {
sum += Math.pow((i % 10), 2);
i /= 10;
}
if (sum == 4) return false;
else if(sum == 1) return true;
else if (sum !=1) {return isHappy(sum);}
else return true;
}
}
My teacher also said the mistake is in the following part:
if (sum == 4) return false;
else if(sum == 1) return true;
else if (sum !=1) {return isHappy(sum);}
else return true;
Please help :)
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class HappyNumbersMain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Lower limit (>0): ");
String st1 = scan.nextLine().trim();
System.out.print("Upper limit: ");
String st2 = scan.nextLine().trim();
int min = Integer.parseInt(st1);
int max = Integer.parseInt(st2);
Set<Integer> happyNumbers = getHappyNumbers(min, max);
System.out.println("Happy numbers between " + min + " and " + max + ":" + happyNumbers);
}
public static Set<Integer> getHappyNumbers(int min, int max) {
Set<Integer> out = new TreeSet<>();
for (int i = min; i <= max; i++) {
if (isHappy(i)) {
out.add(i);
}
}
return out;
}
private static boolean isHappy(int i) {
// Stopping conditions
if (i == 4) {
return false;
} else if (i == 1) {
return true;
}
int sum = 0;
while (i > 0) {
sum += Math.pow((i % 10), 2);
i /= 10;
}
return isHappy(sum);
}
}
Above works as expected, some notes:
When doing recursive functions, put stopping conditions as the first thing it checks
Adding some feedback to the user helps in understanding how to use your program
TreeSet will sort values, HashSet does not, better for display purposes
You should always verify user input (I did not do that, but you should)
if (sum == 4)
return false;
else
if(sum == 1)
return true;
else
return isHappy(sum);
Alternative:
switch ( sum ): {
case 4: return false; break;
case 1: return true; break;
default: return isHappy(sum); break;
}
The break isn't needed, since the return in all control paths.
Question
We consider a word,w , to be beautiful if the following two conditions are satisfied:
No two consecutive characters are the same.
No two consecutive characters are in the following vowel set: a, e, i, o, u, y. Note that we consider y to be a vowel in this challenge.
For example:
The string batman is beautiful because it satisfies the given criteria; however, apple has two consecutive occurrences of the same letter (pp) and beauty has three consecutive vowels (eau), so those words are not beautiful.
My problem is when i am giving an input string "yes" it prints Yes but it should print No.
When i debugged the code using Intellij i see that
It is executing the code which is past return statement but the return statement is used to transfer control to the main function.
Solution
public class Coding {
int count = 0;
public static void main(String[] args) {
Coding obj = new Coding();
Scanner in = new Scanner(System.in);
String w = in .next();
boolean b = true;
char[] c = w.toCharArray();
for (int i = 0; i < c.length - 2; i++) {
b = obj.check(i, c); //recursive function
if (c[i] == c[i + 1]) {
b = false;
break;
}
if (!b) {
System.out.println("No");
break;
}
}
if (c[c.length - 2] == c[c.length - 1]) //check.for.the.remaining.chars
System.out.println("No");
else if (b) {
System.out.println("Yes");
}
}
public boolean check(int i, char[] c) {
if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u' || c[i] == 'y') {
count++;
if (count == 2) {
return false; // code following this statement are executing
}
check(i + 1, c);
}
count = 0;
return true;
}
}
You are making a recursive call, but you are ignoring the results of that call!
That doesn't make sense. Either that call is valid, then you should return whatever comes back. Or the recursion doesn't "belong" there, then you should rework the complete method!
Beyond that: although recursive solution often look elegant, those contests focus on optimal performance. Meaning: rather use a single loop to iterate that string once.
Hint: The problem appears to be with method count. It always returns true to main method. If any recursive call returns false, is it being propagated back to main method?
I'm trying to make a program that returns a letter grade for whatever number grade you put into it but java keeps telling me I'm missing a return statement. I've tried changing char to void to int but none of those worked. I'm still a newbie so any help would be appreciated.
class Grades
{
public static char getGrade(int x)
{
char A, B, C, D, F;
if((x>=90) && (x<=100))
return 'A';
if((x>=80) && (x<=89))
return 'B';
if((x>=70) && (x<=79))
return 'C';
if((x>=65) && (x<=69))
return 'D';
if(x<65)
return 'F';
}
public static char getGrade(int y, int z)
{
int w = ((y + z)/2);
return getGrade(w);
}
public static void main(String[] args)
{
System.out.println("64 gets the grade " + getGrade(64));
System.out.println("99 gets the grade " + getGrade(99));
System.out.println("73 and 91 gets the grade " + getGrade(73,91));
}
}
Every time I use this code I always receive the error:
Grades.java:17: error: missing return statement
}
Why is this?
You should always have a 100% probability to return something, which was not the case here.
public int returnAnInt(int a){
if (a > 0) return 10;
}
This code wouldn't work because it is not guarenteed that a is always superior to 0. Imagine have -1 as a parameter.. What would it return?
Check the correction :
public int returnAnInt (int a){
if (a > 0) 10;
else return 0;
}
Because you're anticipating all the possibilities, this will compile.
You can set F as the default return value here :
public static char getGrade(int x)
{
if((x>=90) && (x<=100))
return 'A';
if((x>=80) && (x<=89))
return 'B';
if((x>=70) && (x<=79))
return 'C';
if((x>=65) && (x<=69))
return 'D';
else
return 'F';
}
It will work in this condition but is not optimal in most situations. It is up to you to find the best correction possible to your own code.
I gave you the right path here.
You're not guaranteed to return anything from your if statement. You have to add an else or return some default value.
If you want to keep the code the same, then place return 'F'; at the end of the method. No need to check if it is an F; it is by elimination.
For instance, that would mean the code would look as follows.
public static char getGrade(int x) {
if((x>=90) && (x<=100)) {
return 'A';
}
if((x>=80) && (x<=89)) {
return 'B';
}
if((x>=70) && (x<=79)) {
return 'C';
}
if((x>=65) && (x<=69)) {
return 'D';
}
return 'F';
}
As an alternative, consider including else if statements, since that would make this a bit clearer.
The compiler cannot ensure that there is a return. Have a look at the following example:
public boolean mod2(int a){
if(a % 2 == 0)
return true;
if(a % 2 != 0)
return false;
}
This method will return for any given value but the compiler can only check snytax not semantics. And therefore the code is not compilable.
You need something like a default case which will match if none of the above statements will match.
With the code above it will be:
public boolean mod2(int a){
if(a % 2 == 0)
return true;
else
return false;
}
Note that you can avoid repeating the grade boundaries by using TreeMap:
public static char getGrade(int x) {
NavigableMap<Integer, Character> grades = new TreeMap<Integer, Character>();
grades.put(90, 'A');
grades.put(80, 'B');
grades.put(70, 'C');
grades.put(65, 'D');
grades.put(Integer.MIN_VALUE, 'F');
return grades.floorEntry(x).getValue();
}
If you know that the number grades are non-negative, you can replace Integer.MIN_VALUE with 0 for better readability.
If, on the other hand, you want the method to reject number grades higher than 100, you will need to add some validation at the top of the method.
If the grade calculation is performance critical, it is better to initialize the map just once, somewhere outside the getGrade method.
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 7 years ago.
Improve this question
All of my methods after the main are getting "illegal start of expression" error messages and I can't figure out why. Here is my code:
import java.util.Scanner;
public class CreditCardCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// This program allows the user to enter multiple credit card numbers, then
//tallys and displays the number of each different brand of credit card entered.
// Create a new scanner.
Scanner input = new Scanner(System.in);
System.out.print("Enter your Card Number : ");
long input = sc.nextLong();
if (isValid(input) == true) {
System.out.println("\n*****Your card is Valid*****");
} else {
System.out.println("\n!!!!Your Card is not Valid !!!!! ");
}
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=13 ) && (getSize(number)<=16 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
You have a two problems that are preventing you from building.
First, input is defined as both a Scanner and a long. You can't have the same name for two different things like that. Based on the line where you initialize the long input, I'm guessing your Scanner is supposed to be named sc.
Next, you don't have a closing brace for your main method.
Fixing these two errors appears to remove the build errors. You'd still need to text your logic, however.
Seems that you forgot a curly bracket:
...
if (isValid(input) == true) {
System.out.println("\n*****Your card is Valid*****");
} else {
System.out.println("\n!!!!Your Card is not Valid !!!!! ");
}
} // <--- add this bracket
I am trying to make a cee-lo program in simple, simple java. I'm just learning. However when I get to my instant w. (i have simplified it for the test) it just always returns false. I can't seem to figure out why. It even displays the correct data but when it compares it it fails.
public class ceeLo
{
public static void main (String [] args)
{
Scanner scan= new Scanner (System.in);
int [] die = new int [3];
int answer;
boolean roll = true;
boolean qualifed;
boolean instantW;
boolean instantL;
do
{
System.out.println("Roll the dice?");
answer = scan.nextInt ();
if (answer == 0)
roll= false;
else
{
int i;
for (i = 0; i < die.length; i++)
{
die[i]= rollin();
System.out.println(diceTxt(die[i]));
}
qualifed = (qualify (die));
System.out.println("Qualified = " + qualifed);
instantW = (easyW (die));
System.out.println("Instant win = " + instantW);
}
}
while (roll);
}
// Generate random numbers for the roll
public static int rollin ()
{
Random rand = new Random();
int die= rand.nextInt(6);
return die;
}
//Check if dice qualify with pair
public static boolean qualify (int [] die)
{
boolean qualify;
//Pair Qualifying roll
if (die[0] == die[1] || die[0] == die[2] || die[1] == die[2])
qualify = true;
else
qualify = false;
return qualify;
}
//Check if instant win
public static boolean easyW (int [] die)
{
boolean instantW;
// show contents of die [x] for testing
System.out.println (die[0] + "" + die[1] + "" + die[2]);
if (die[0] > 2 && die [1] > 2 && die[2] > 2)
instantW = true;
else;
instantW = false;
return instantW;
}
}
Remove semi-colon after else; it should be just else
I guess the reason is,
instantW = false; is being treated as separate statement not part of else block. Which is why instantW is always being assigned to false and returning false.
It is always better to use {} to define block even though they are single liners. It is my preference.
As Greg Hewgill suggested, using single statement instantW = die[0] > 2 && die [1] > 2 && die[2] > 2; would do good than if/else.
A better way to write boolean methods is really to do something like
boolean easyW(int[] die)
{
return (die[0] > 2 && die[1] > 2 && die[2] > 2);
}
Or even better (more general)
boolean easyW(int[] die)
{
for(int roll : die)
{
if(roll < 2)
{
return false;
}
}
return true;
}
But in your case, you have a ; after your else. Fixed version:
public static boolean easyW (int [] die)
{
boolean instantW;
// show contents of die [x] for testing
System.out.println (die[0] + "" + die[1] + "" + die[2]);
if (die[0] > 2 && die [1] > 2 && die[2] > 2)
instantW = true;
else
instantW = false;
return instantW;
}