methods in Java will not work? - java

So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.

As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.

In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.

/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}

Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}

Related

How do I use the interface for this number reverse program, instead of using the program entry itself? (JAVA)

I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}

About Java function calling

Could someone explain to me when I run this code, I don't get the Sysout statement until I enter my first keyboard input?
import java.util.Scanner;
public class test1{
static Scanner scan = new Scanner(System.in);
static int k = scan.nextInt();
public static void main(String[] args) {
setK();
System.out.println(" K is: " + k);
}
public static void setK(){
System.out.println("Please input K value");
k = scan.nextInt();
}
}
The static variables of your test1 class are initialized before your main method is executed. This happens when the class is initialized.
Therefore the
static int k = scan.nextInt();
statement is executed before your main method and waits for input. Only after the input is entered, main starts running and calls setK();, which prints "Please input K value".
I'm not sure this was intentional, since your setK() method seems to be the method that should read the input and assign it to k. Therefore, change your code to :
import java.util.Scanner;
public class test1{
static Scanner scan = new Scanner(System.in);
static int k;
public static void main(String[] args) {
setK();
System.out.println(" K is: " + k);
}
public static void setK(){
System.out.println("Please input K value");
k = scan.nextInt();
}
}
This line
static int k = scan.nextInt();
runs during class initialization. It blocks and waits for input of an integer.
This code runs before main because it is a static initialization. It must be complete before the first method of the class is called. At that point k has the first value you have entered. After that, main calls setK, prompting for another input.
You can fix this by removing initialization (i.e. the = scan.nextInt(); part) from declaration of k.
Maybe the behaviour you expect would be as follows:
package test;
import java.util.Scanner;
public class ScannerTest {
static Scanner scan = new Scanner(System.in);
static int k;
public static void main(String[] args) {
System.out.println("Please input K value");
k = scan.nextInt();
System.out.println(" K is: " + k);
}
}
BTW, you should stick to Java naming conventions.

User input in Factorial Recursion?

So I'm trying to make a program where the user inputs a number and the computer outputs the factorial. I have to use recursion and have 1 class and 1 client.
My class is:
public class Factorial
{
public static int Factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*(Factorial(n-1));
}
}
}
My client is:
public class FactorialClient
{
public static void main()
{
Factorial n = new Factorial();
System.out.println(n.Factorial(4));
}
}
These both compile and work completely fine. However, I'm trying to figure out a way for the user to input the number instead of my inputting the number inside the client. Please help!
Try this.
public class FactorialClient
{
public static void main()
{
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int x = reader.nextInt();
Factorial n = new Factorial();
System.out.println(n.Factorial(x));
}
}
The Scanner class is great for reading user input.
The following should work:
public class FactorialClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();
System.out.println(Factorial.Factorial(userInput));
}
}
Note that you don't have to declare a new Factorial object because the Factorial method has been declared static.

Creating a for loop that reduces long intergers to a number between 0 and 101

I am trying to create a for loop in Java that will take a long integer and reduce it to a value between 0-101. For example the number 89123 would be reduced to 89 and 10145 would be reduced to 101. I know that this can be done by continuously dividing the longer integer by 10 but I do not know how to write the loop so that it stops when the integer is somewhere in the range of 0-101. Any help is appreciated, thanks!
Something like this:
public class Test {
public static long getNumber(long input) {
while(input > 101) {
input = input /10;
}
return input;
}
public static void main(String[] args){
System.out.println(getNumber(101111));
System.out.println(getNumber(89123));
}
}
Something like this:
import java.util.Scanner;
public class HelloWorld{
public static Scanner scanner = new Scanner(System.in);
public static void main(String []args){
long number;
System.out.print("Enter number (to exit enter -1):");
while((number = scanner.nextLong()) != -1){
while(number > 101){
number /= 10;
}
System.out.println(number);
System.out.print("Enter number (to exit enter -1):");
}
}
}
this should work.
public int getNumber(long l){
int lenght=(""+l).length();
if(length<3)return (int)l;
l/=(int)Math.Pow(10,length-3)
if(new Long(l).equals(101)||new Long(l).equals(100))return (int)l;
else return (int)(l/=10);
}

What are the errors here?

import java.util.Scanner;
public class program4
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled;
System.out.println("Your result is" + doubleNumber(number));
System.out.println(" thank you for using my program ");
}
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
if (integerDoubled < 100 ); {
less_100(integerDoubled);
} else if ;
greater_100(integerDoubled);
public static int less_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*2);
}
public static int greater_100 (int integerDoubled)
{
int integerDoubled;
return integerDoubled =(x*3);
}
}
}
I think the error is in the If statement but i don't know how to fix it.
I know integerDoubled is a local variable and i should make it global but I'm not sure how to do that. should i put the if statement together with the doubleNumber function??
If you formatted your code (your IDE will do this for you), you would see that the if statement is not inside a method as it must be. If you use your IDE correctly, finding and correcting such error would be much faster and you barely have to think about it.
I tried to make sense of your program this is what I came up with
import java.util.Scanner;
public class T
{
public static int doubleNumber (int x){
int integerDoubled;
return integerDoubled = (x*2);
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println(" Hello and welcome to the program ");
System.out.println("Enter your number.");
int number = input.nextInt();
int integerDoubled=doubleNumber(number);
System.out.println("Your result is" + integerDoubled);
System.out.println(" thank you for using my program ");
if (integerDoubled < 100 ) {
less_100(integerDoubled);
}
else
greater_100(integerDoubled);
}
public static int less_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*2);
}
public static int greater_100 (int integerDoubled)
{
return integerDoubled =(integerDoubled*3);
}
}

Categories