I'm a first year programmer and not completely certain on what I'm doing wrong with this code. Please, can anyone help?
package ________;
public class _______
{
public static void main(String[] args)
{
public int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
}
This line displays an illegal start of expression method every time I attempt to compile or run the program:
public int getFactorial(int number)
The ____'s just represent the hidden package and class names. Using NetBeans IDE 7.4, Java apllication
You cannot have other methods or functions inside the main function. You can however call the functions from your main function.
Please write the code as
public static void main(String[] args)
{
int number = 10;
/* if you want user to input */
Scanner get = new Scanner(System.in);
number = get.nextInt(); // get the next integer user types :)
getFactorial(number);
}
public static int getFactorial(int number)
{
int factor = 1;
if (number == 1)
{
System.out.println("Returned 1");
}
else
{
factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
}
return factor;
}
This way, your function would be inside the same Class but outside the bounds of Main method. In the main method, you would be calling it and where the control would be transfering to the getFactorial function.
You have a method (getFactorial) inside another (main). They need to come one after another.
public static void main(String[] args){
getFactorial(int number);
}
public static int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
You can't write a method inside another method. Your code should look like this:
package ________;
public class _______ {
public static void main(String[] args) {
//call getFactorial, for example
int result = getFactorial(2);
}
public static int getFactorial(int number) {
if (number == 1) {
System.out.println("Returned 1");
return 1;
} else {
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
Related
This is an homework problem
Is there a way tor reverse a number in Java without using any loops? The only solution I can think of is reversing it using String and then casting it back to an integer.
If you want to reverse a number withour using any loop you can use Recursion method call. Following program is doing same
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
} else {
System.out.print(number % 10);
reverseMethod(number / 10);
}
}
public static void main(String args[]) {
int num = 4567;
reverseMethod(num);
}
Even if you were to reverse the number by casting it into a String, you would still need a loop if you want the program to work when having ints of different sizes. If I were to make a method to reverse a number but could not do it with loops, I would probably do it with recursion (which still uses loops indirectly). The code will look something like this:
class Main {
public static void main(String[] args) {
String input = "1234"; // or scanner to take in input can be implemented
System.out.println(Integer.parseInt(reverseInt(input)));
}
public static String reverseInt(String x) {
if (x.length() == 1) {
return x;
} else {
return x.substring(x.length() - 1) + reverseInt(x.substring(0, x.length() - 1));
}
}
}
Hope this helps!
By using reverse() of StringBuilder:
int number = 1234;
String str = String.valueOf(number);
StringBuilder builder = new StringBuilder(str);
builder.reverse();
number = Integer.parseInt(builder.toString());
System.out.println(number);
will print:
4321
if you want reverse method without loop and recursion then use this code
int a=12345;
int b,c,d,e,f;
b=a%10;
c=a%100/10;
d=a%1000/100;
e=a%10000/1000;
f=a%100000/10000;
System.out.println(b+","+c+","+d+","+e+","+f);
you can go like :
public int reverse(int x) {
String o = "";
if (x < 0) {
x *= -1;
String s = Integer.toString(x);
o += "-";
o += new StringBuilder(s).reverse().toString();
}
else {
String s = Integer.toString(x);
o += new StringBuilder(s).reverse().toString();
}
try {
int out = Integer.parseInt(o);
//System.out.println(s);
return out; }
catch (NumberFormatException e) {
return 0;
}
}
This is a solution using recursive method call
public class Tester{
public static int findReverse(int num, int temp){
if(num==0){
return temp;
}else if(num<10){
return temp*10 + num; //up to this is stopping condition
}else{
temp = temp*10 + num%10;
return findReverse(num/10, temp);
}
}
public static void main(String args[]){
int num = 120021;
int reverseNum = findReverse(num, 0);
System.out.println(reverseNum);
if(num == reverseNum)
System.out.println(num +" is a palindrome!");
else
System.out.println(num +" is not a palindrome!");
}
}
This will be fast.
static int reverseNum(int num) {
StringBuilder sb = new StringBuilder(String.valueOf(num));
sb.reverse();
return Integer.parseInt(sb.toString());
}
I've got 2 integer values, e.g. a = 10 and b = 20.
Now i want to substract them: a - b, but as a result i don't want to have negative values, so in this example i want the result 0 and a new integer variable with the rest (10 here).
Two more examples:
Input: a=40, b=20; Expected Output:20
input: a=25 b=50 Expected Output: 0 and a new int var = 25
How to do this in java without external libraries?
From what I understand, you want a variable to be holding the result if the result is greater than or equal to 0. Otherwise, that variable should hold 0 and another variable will hold a positive value of the result.
If this is the case, consider the following code snippet:
int result = a -b;
int otherVariable = 0;
if (result < 0) {
otherVariable = -result;
result = 0;
}
int aMinusB = a-b;
int output = Math.max(aMinusB,0);
int rest = aMinusB < 0 ? Math.abs(aMinusB) : 0;
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
There are two ways to solve this problem: -
First: -
If you don't want to create a method to return this value and only to display it, then you can do it by printing out the results of if-else block in the code below within the function itself.
Second: -
If you want to use the result somewhere else, go for an object based approach: -
// Main class
public class SubtractWithRest {
public static void main(String[] args) {
SubtractResultWithRest subtractResultWithRest = new SubtractResultWithRest();
subtraction(10, 20, subtractResultWithRest);
System.out.println("Result: " + subtractResultWithRest.getResult());
System.out.println("Rest: " + subtractResultWithRest.getRest());
}
private static void subtraction(int num1, int num2, SubtractResultWithRest subtractResultWithRest) {
if (num2 > num1) {
subtractResultWithRest.setResult(0);
subtractResultWithRest.setRest(num2 - num1);
} else {
subtractResultWithRest.setResult(num1 - num2);
}
}
}
// Object class
public class SubtractResultWithRest {
private int result;
private int rest = 0;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public int getRest() {
return rest;
}
public void setRest(int rest) {
this.rest = rest;
}
}
The task is to find the prime number at a given number. Here is the code
import java.util.ArrayList;
public class Queue {
private static int number = 0;
private static int prime;
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
{
number++;
}
}
System.out.println(number );
}
public static void main(String args[]) {
calculatePrime(10001);
}
}
when the input value is 3 it prints out the correct value of 5 but when the input value is 10001 it prints out a number other than 104743
Here's your calculatePrime method as the compiler sees it:
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
number++;
}
System.out.println(number );
}
You could use something like this:
public static void calculatePrime(int p) {
int primeCandidate = p;
while (!isPrime(primeCandidate)) {
primeCandidate++;
}
System.out.println(number );
}
And you'll need a method to return true if the candidate is a prime. There are loads of these available for the small price of a google search.
Why This code is not giving compile time error
package com.test;
public class Recursive {
public static int name(int number) {
if (number <= 0)
return 0;
return 1 + name(number / 10);
}
public static void main(String[] args) {
System.err.println(name(124));
}
}
Because you did not write the brackets. Each loop, if or else can be followed by a block of code ({...}) or a single statement. So your code is equivalent to:
package com.test;
public class Recursive {
public static int name(int number) {
if (number <= 0) {
return 0;
}
return 1 + name(number / 10);
}
public static void main(String[] args) {
System.err.println(name(124));
}
}
Your code is equivalent to
if (n <0) {
return 0;
}
return 1 + name (n/10);
This completely legal code
The reason there is no compile time error is because your code is syntactically correct. If the code is not doing what you expected, please explain how.
I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)