I am new to JAVA. I want to create a class and write a function in it. I then want to use that function in the main class.
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
Addition obj = new Addition();
c = obj.add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
The problem I think according to error message you mentioned in the comments:
Exception in thread "main" java.lang.NoSuchMethodError:
Addition.add(II)I at multi_fun.main(multi_fun.java:15)
It seems that you are putting class Addition declaration in the same source file of multi_fun.java program.
You should create a java class file called Addition.java and put your class code in it:
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
After that it should work without any errors.
Update:
You can check this Answer which explain Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'it would be a useful solution to your problem.
Make sure both the java files are in the same folder.
MultiFun.java
import java.util.Scanner;
public class MultiFun {
public static void main(String[] args) {
Addition obj = new Addition();
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
c = obj.add(a, b);
System.out.println("The sum is " + c);
scan.close();
}
}
Addition.java
class Addition {
public int add(int a, int b) {
return (a + b);
}
}
run the following commands
javac MultiFun.java
java MultiFun
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
public static int add (int a, int b)
{
return(a+b);
}
The reason for this error is that there was already an other file in the same folder named Addition. So when I wrote a Class with the same name and tried to create an object, it was giving error message, as the parameters where different.
Thank you everyone for your help.
If you are run your program using Terminal or command prompt(cmd) make sure to run the class that have main method(created object from Addition class). And also do not create main methods in both classes and do not add public to Addition class.
One last thing: compile and run only the main class(multi_fun). Which is,
javac multi_fun.java
java multi_fun
Related
Hello
I'm new to java and need someone to answer a problem I'm having. I have recently started a project to make a calculator in Java. However i'm having a problem with one prat of my code. Basically i can't call a string off from an method. Ive tried varoius other attemps to fix the problem but to no avail. Here is the code:
package CalculatorCore;
import java.util.Scanner;
public class calculations {
static void firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
String n1 = firstNum.next(); //You can see, i put the string in a method
}
static void secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
String n2 = secondNum.next(); //Here too
}
public static void main(String[] args) {
System.out.println("Please Choose one of the following equasions: +, -, * or /");
System.out.println("");
System.out.println("");
mathEquasions();
}
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
firstNumber();
System.out.println("");
System.out.println("Now add the second number");
secondNumber();
var plusAnswer = (n1 + n2); /*The problem is situated here, i need to call the
strings from another class*/
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
firstNumber();.n1
}
}
I've already used methods to make the user inputs compact so if theres no other way should i remove the methods?
You need to return the numbers you retrieved in your both methods. Don't forget to parse them as integers, using nextInt:
public class calculations {
static int firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
int n1 = firstNum.nextInt();
return n1;
}
static int secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
int n2 = secondNum.nextInt();
return n2;
}
}
Then, when calling firstNumber or secondNumber, create new variables to store their return values:
public class calculations {
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
int n1 = firstNumber();
System.out.println("");
System.out.println("Now add the second number");
int n2 = secondNumber();
var plusAnswer = (n1 + n2);
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
}
}
}
welcome to SO! When trying something for the first time it's a good practice to make it as simple as you can, and from there gradually use more complex techniques.
In this case everything is in one class already, so as a first step you could try to put all your code back into the main method.
public static void main(String[] args) {
//All your code can come here first in the order they are supposed to to be called.
}
As a second step, when it all works, you can extract the parts where you would duplicate code, into separate methods.
Like here instead of having firstNumber() and secondNumber() you could have just one, with something like:
static int getNumber() {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int number = scanner.nextInt();
return number;
}
and you can call the same method to get both numbers:
public static void main(String[] args) {
//...
System.out.println("Please enter the first number that you want to add");
int n1 = getNumber(); // Using the same method for both
System.out.println("");
System.out.println("Now add the second number");
int n2 = getNumber(); // Using the same method for both
//...
}
Learning by doing and jumping into the thick of it is one of the best ways to learn. There are tons of good quality materials freely available (eg. on yt) and they can really boost your skills. That's also how I started learning, so good luck!
I was making a program to reduce given integers to their simplest ratio.But an error is occurring while taking inputs through Scanner class in a sub-method of program.Here is the code :
package CodeMania;
import java.util.Scanner;
public class Question5
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();// number of test cases
sc.close();
if(T<1)
{
System.out.println("Out of range");
System.exit(0);
}
for(int i=0;i<T;i++)
{
ratio();//line 19
}
}
static void ratio()
{
Scanner sc1=new Scanner(System.in);
int N=sc1.nextInt();//line 26
if((N>500)||(N<1))
{
System.out.println("Out of range");
System.exit(0);
}
int a[]=new int[N];
for(int i=0;i<N;i++)
{
a[i]=sc1.nextInt();
}
int result = a[0];
for(int i = 1; i < a.length; i++)
{
result = gcd(result, a[i]);
}
for(int i=0;i<N;i++)
{
System.out.print((a[i]/result)+" ");
}
sc1.close();
}
static int gcd(int a, int b)
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
The error is--
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at CodeMania.Question5.ratio(Question5.java:26)
at CodeMania.Question5.main(Question5.java:19)
Here I have used 2 seperate scanner objects sc in main function and sc1 in ratio function to take input from console.
However if I am declaring a public static type Scanner object in class scope and then using only one Scanner object throughout the program to take input then program is working as required without error.
Why this is happening...?
The reason for this error is that calling .close() on the scanner also closes the inputStream System.in, but instantiating a new Scanner will not re-open it.
You need to either pass a single Scanner around in your method parameters, or make it a static global variable.
Since your main() and your ratio() method are using Scanners they throw exceptions,when an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where exception occurs.
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.
You can handle these exceptions by using Try/Catch blocks,or you can handle them by using the word throws after your method's definition,
in your case these two approaches are going to be like this:
With Try/Catch :
public static void main()
{
try{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();// number of test cases
sc.close();
}
catch(NoSuchElementException e){
System.out.print("Exception handled" + e);
//rest of method
}
static void ratio(){
try{
Scanner sc1=new Scanner(System.in);
int N=sc1.nextInt();}
catch(NoSuchElementException e){
System.out.print("Exception handled" + e);}
//rest of method
}
With "throws":
public static void main()throws Exception{
//rest of method
}
static void ratio()throws Exception
{
//rest of method
}
Try this one. You can pass the scanner as argument
package stack.examples;
import java.util.Scanner;
public class Question5 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();// number of test cases
if (T < 1) {
System.out.println("Out of range");
System.exit(0);
}
for (int i = 0; i < T; i++) {
ratio(sc);// line 19
}
sc.close();
}
static void ratio(Scanner sc1) {
int N = sc1.nextInt();// line 26
//Your Logic
}
static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
import java.util.*;
public class Understanding_Scanner
{
public static void main()
{
Scanner sc= new Scanner(System.in);
System.out.println("Please enter your name");
String name=sc.next();
System.out.println("Your name is:"+name);
}
}
Now to explain this thing so we have to import a scanner class from the Java Utility package so this can be achieved by the code on the first line
the second line is creating a class NOTE (THE NAME OF THE CLASS NEED NOT START WITH CAPITAL) now coming to the main topic Scanner class so for this we must create a scanner class within the program with the code that's been given in the 4th line... in this statement 'sc' is an object which stores the values of the scanner class so if you want to do any operation in the scanner class you can do it via the object 'sc' *NOTE(You can name ur object as anything eg:poop,bla etc)...
then we have this interesting command which says System.in now this allows users to write any statement through the keyboard or any such input devices during run time....
String name=sc.next() this line helps us to write any string that we want to write during the run time, which will b stored in the name variable
So that's it, this is the scanner class for u. Hope its easy to understand.
cheers!! Keep coding :-)
I want to make sum of two numbers. But I have problems to do that. I don't understand why my sum is always zero.
import java.util.*;
public class Numbers {
static int a;
static int b;
static int result;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Type the first number:");
String a = in.nextLine();
System.out.println(a);
System.out.println("Type the second number:");
String b = in.nextLine();
System.out.println(b);
display();
}
public static void display(){
result=a+b;
System.out.println("Sum of numbers is " + result);
}
}
I'm not a java programmer, but I can see that you have global variables called a and b and local variables called a and b.
Your main() is setting the local variables. display() is reading the global variables.
You don't need static "global" variables in your case. So you can remove this piece of code :
static int a;
static int b;
static int result;
Then, juste use your local variables and give a and b as parameter to display() method like this :
public static void display(int a, int b){
System.out.println("Sum of numbers is " + (a+b));
}
Eventually, you will need to cast Strings obtained via in.nextLine() and cast them to int, with Integer.parseInt() for example. Or just directly get integer from the user.
You did couple of mistakes :
String a and String b is a local variable to main() method. So you cant access
those variables from display() method. result=a+b;in display() method is actually adding a and b which are declared in the class level whose by default value is 0. so summation is 0.
Even if you write result=a+b;inside main method it will not work. Because a and b are String in main method and you cant do addition on String
Use this code
import java.util.*;
public class NewClass {
static int a;
static int b;
static int result;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Type the first number:");
a = in.nextInt();
System.out.println(a);
System.out.println("Type the second number:");
b = in.nextInt();
System.out.println(b);
display();
}
public static void display(){
result=(a+b);
System.out.println("Sum of numbers is " + result);
}
}
Use nextInt in place of nextLine method .If the type is int then use nextInt method.
I just want to know how to call methods/functions in java. Can you please help me with this?
So here's my code.
import java.util.Scanner;
public class MyFirstProject {
public static void main(String[] args) {
hello();
}
static void hello(int a, int b) {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
a = scan.nextInt();
System.out.print("Enter second number: ");
b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
}
You make the method hello static for the class MyFirstProject so it has connotations -> Explanation.
But the problem here is that you are missing to pass parameters to the method:
int example_arg_one = 3;
int example_arg_two = 5;
MyFirstProject.hello(example_arg_one,example_arg_two);
2 clicks away, here's a pictured answer - http://www.wikihow.com/Call-a-Method-in-Java
In your code what you're actually missing is passing the required parameters - the values for a and b. The call should actually look like MyFirstProject.hello(2, 5)
Since your method hello(int a, int b) has a parameter of two integers, you need to give it the integers when calling it in order for it to work. But that also doesn't make sense since you have a Scanner which defines your integers in your method. Just remove the parameters of your method and your code should work.
public static void main(String[] args) {
hello();
}
static void hello() {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
int a = scan.nextInt();
System.out.print("Enter second number: ");
int b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
Regarding how to call methods, you're doing it right. Just do not neglect your parameter, if your method has one you have to give it one. If you do not know what a parameter is, it is the hello (int a, int b). Your method is expecting you to give it two integers, because that is how you defined your method, you defined it to take two integers. If you want to call it using the parameter, call it in your main and give it two integers, for example hello(1, 2)
Note: If you want to do that you have to remove the scan.nextInt() from your code.
You forgot to pass two parameters a and b into method hello.
public static void main(String[] args) {
int a = 1;
int b = 2;
hello(a,b);
}
I have a problem statement
Problem
Write a program to calculate the sum of 2 numbers and print the output.
Input
Line 1: An integer.
Line 2: An integer.
Output :The output consists of a single integer which corresponds to sum, followed by a new line
Sample Input I
3
1
Sample Output I
4
Sample Input II
13
10
Sample Output II
23
To which my solution is
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Add {
public static void main(String[] args)throws IOException
{
int a=0, b=0, sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the numbers to be summed");
try{
a=sc.nextInt();
sc.nextLine();
b=sc.nextInt();
}
catch(InputMismatchException e){
System.out.println("Please enter an Integer number");
e.printStackTrace();}
catch(Exception e){System.out.println(e);}
sum=a+b;
System.out.println(sum);
sc.close();
}
}
I'm supposed to submit it to an online directory, that I assume tries to execute the program automatically. And when I do, it tells me
Wrong Answer Almost there,think some more
I think pondering over it for an hour is more than enough before you decide to call in for reinforcement.
The output should be "a single integer which corresponds to sum, followed by a new line".
But the output of your program is
Enter the numbers to be summed
<the sum>
remove sc.nextLine(). It makes it move to the next line, but since both integers are on the same line, the value for b remains at 0.
These can be solve by two thing command line arguments or Scanner class or BufferReader.
Using the Command line Arguments.
public Class Sum
{
public static void main(String [] args)
{
int a ,b,c;
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= a+b;
System.out.println("The Sum of two number is : "+c);
}
}
Using Command Line Arguments with code re usability(Method Sum)
public Class Sum
{
public static long sum(int a,int b)
{
return a+b;
}
public static void main(String [] args)
{
int a ,b;
long c; // for long summation of numbers .
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= sum(a,b);
System.out.println("The Sum of two number is : "+c);
}
}
Using the External resources from the java.util.Scanner
public Class Sum
{
public static void main(String [] args)
{
int a ,b;
long c;
Scanner scan;
scan = new Scanner(System.in) ; //Taking system Keyboard for input.
System.out.println("Enter the value of A: \n");
a= ss.nextInt() ;
System.out.println("Enter the value of B: \n");
b=ss.nextInt();
c= (long) (a+b);
System.out.println("The Sum of two number is : "+c);
}
}
Try this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int sum = 0;
System.out.println("Enter Number: ");
num1 = in.nextInt();
System.out.println("Enter Number2: ");
num2 = in.nextInt();
sum = num1 + num2;
System.out.println(sum);
}
}
package stack;
public class Satck {
public static int MAX=100;
int top;
int [] a= new int [MAX];
boolean empty()
{
return (top<0);
}
Satck()
{
top=-1;
}
void push(int x)
{
a[++top]=x;
}
public int pop()
{
int x=a[top--];
return x;
}
public int peek()
{
int x=a[top];
return x;
}
public static void main(String[] args) {
Satck s=new Satck();
s.push(10);
s.push(11);
s.push(12);
s.push(13);
System.out.println(s.peek());
System.out.println(s.empty());
System.out.println(s.pop());
System.out.println(s.peek());
}
}