当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to return new number from method to the main

问题描述:

I'm new in java.

I have to write a program that modifies an existing catalog (3-5 digits) number to a new catalog number by adding a number to the left of an existing catalog number according to these conditions:

  1. The new number wiil be the largest number between the leftmost digit to the rightmost digit.
  2. If leftmost digit equal to the rightmost, the new number will be 9.

The input should be 10 numbers and then to add a new number.

The problem is that, now, the method "newKatalogNumber" get the old catalog number, and return the left digit, i like the method return the new catalog code according to the conditions (now the conditions are in the main). for instance, if the method get 1234, she will return 41234, and it will be printed at the end of the main. I have not found a way to do it.

Is enybody have the clue how to do that?

I will be grateful.

This is my code:

import java.util.Scanner; // This program gets an old catalog number between 3 to 5 digits and change it to a new catalog number

// by adding a new digit to the left of the number

public class Number

{

public static int newKatalogNumber(int num)

{

while (num>=10)

{

num /= 10;

}

return num;

}

public static void main(String[] args)

{

Scanner input = new Scanner(System.in);

for (int oldNum=0; oldNum<10; oldNum++)

{

System.out.print("Insert old catalog Number: ");//The user insert the old catalog number

int catalogNum = input.nextInt();

int mostRight = catalogNum % 10;

int mostLeft = newKatalogNumber(catalogNum);

//Adding the new digit according to condition below:

if (mostRight>mostLeft)

{

System.out.println("Old catalog number is:"+catalogNum);

System.out.println("New catalog number is"+mostRight+catalogNum);

}

else if (mostLeft>mostRight)

{

System.out.println("Old catalog number is:"+catalogNum);

System.out.println("New catalog number is"+mostLeft+catalogNum);

}

else

{

System.out.println("Old catalog number is:"+catalogNum);

System.out.println("New catalog number is"+9+catalogNum);

}

}

}

}

网友答案:

You can make a static method that does all the computation and returns you the result in main()

public static int doComputation(int someNumber){
  // your logic
  return result;
}  

Inside your main, you can do as follows:

int whatIGetBack = doComputation(5);  
System.out.println("Result in main() " + whatIGetBack);
网友答案:

You can shuffle the number to front by multipliying by 10 enough times

public static int newKatalogNumber(int num)  
{
    int original = num;
    int multiplier = 1;
    while (num>=10) 
    {
        num /= 10;
        multiplier *= 10;
    }


   return (num * mulitplier) + original;
}

Another approach would be to convert to strings and use string concatenation.

分享给朋友:
您可能感兴趣的文章:
随机阅读: