Error with return - java

I'm trying to do a input dialog, if the input number is bigger than 10 it should print a special message. So I inserted the return, but then I get this error: unexpected return value.
Here is the code:
import javax.swing.JOptionPane;
public class Program extends JFrame {
public static void main(String[] args) throws IOException {
int number= Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
if(number> 10)
return System.out.println("The number must be less that 10");
else
System.out.println("...");
}
}
Sorry for my bad English.

What you should do is print the error message on the error stream, and exit with an error code, like so:
public class Program extends JFrame {
public static void main(String[] args) throws IOException {
int number= Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
if(number> 10) {
System.err.println("The number must be less that 10");
System.exit(1);
} else {
System.out.println("...");
}
}
}

You have wrongly understood the return concept.
Since the main method's return type is void there will be no return.
if(number> 10)
System.out.println("The number must be less that 10");
else
System.out.println("...");
You are just printing to console. So there is no need of that return statement.
As a side note use always {} for if -else

There are two core errors here:
main is a void method so you can't return anything from it
System.out.println is a void method so you couldn't return it anyway
Drop the return bit completely and just print the result you want instead, or make it a separate String method and return the result instead of printing it. If you want your program to terminate after a faulty input, just add a simple lone return:
if(number> 10) {
System.out.println("The number must be less that 10");
return;
}
else //..and so on

Here you are trying to return a value from a void method(i.e. public static void main(String[] args), which is completely invalid.
I would sugest you to consider other other class completely for this thing and then call the methods from some other class consisting the main method.

the main method is void, it can not return anything, nor is it supposed to.
just remove the "return" keyword, and keep the print statement.

Related

Formatting double as a function parameter

I have a function that takes in a double as a paramater. However, if I input "8" when I call the function, it processes as "8.0".
I know that I can format it with String.format() and other methods, however the format that the number is inputted as is important to the result (8 has a different result than 8.0, and I have no idea inside of the function body which one was intended by the user).
I know that I can add a format parameter as well as the double, function(double d, DecimalFormat f), but that would make it much more tedious to use, and it is intended as a util function anyways. Any tips?
There are some ways you can solve this, depending on your problem.
Method overloading
If the user input is by code, you can handle different types using the same method name.
class Program {
public static void foo(int n) {
// The input is an integer
System.out.println(n);
}
public static void foo(double x) {
// The input is a double
System.out.println(x);
}
public static void main(String[] args) {
foo(8); // prints 8
foo(8.0); // prints 8.0
}
}
Handling strings
However, if the user input is by keyboard, for example, you can use RegEx.
class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
if (input.matches("^\\d+\\.\\d+$")) {
// The input is a double
} else if (input.matches("\\d+")) {
// The input is an integer
} else {
// The input is something else
}
}
}

Program not working?

The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates.
There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct.
import java.util.*;
class yearst
{
int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y;
i=1;s1=0;s2=0;s3=0;diy=365;
void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
ob.leap(i+1)
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
ob.leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
ob.leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s)
}
}
Please help.
Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :-
import java.util.*;
class yearst
{
static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y;
static void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
//i=1;s1=0;s2=0;s3=0;diy=365;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
leap(i+1);
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s);
}
}
All the Best :)
Only declarations and static blocks allowed out of the methods. The below executable statement must be either in static block or in constructor
int i=1,s1=0,s2=0,s3=0,diy=365;
So, I recommend you move above code to constructor.
yearst(){
i=1;s1=0;s2=0;s3=0;diy=365;
}
A few things:
You'll need to initialize your variables inside a constructor, as initializing inside a class isn't allowed
Have you checked out the Date class in Java? It might be more useful for this case.
According to convention, class names should start with a capital letter

print out each character in an input

I've been teaching myself Java with http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html as a reference. They have a library called algs4 and it has several classes including StdIn, which I'm trying to implement below.
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Tired
{
public static void main(String[] args)
{
//I thought this while statement will ask for an input
//and if an input is provided, it would spell out each character
while (!StdIn.hasNextChar()) {
StdOut.print(1); //seeing if it gets past the while conditional
char c = StdIn.readChar();
StdOut.print(c);
}
}
}
//This is from StdIn class. It has a method called hasNextChar() as shown below.
/*
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
*/
If i run the code, it does ask for an input, but regardless of what i type in, nothing happens and nothing gets printed out.
I see that even StdOut.print(1); doesnt get printed out, so for some reason, it just gets stuck on while
It looks like the issue is with the condition for your while loop:
!StdIn.hasNextChar()
This says to continue as long as there isn't a next char. But you want to continue while there is one, so get rid of that ! and you should be good.
Here is some alternative code that works similarly. Not the best coding but works.
import java.util.Scanner;
public class test{
static Scanner StdIn = new Scanner(System.in);
static String input;
public static void main(String[] args){
while(true){
if(input.charAt(0) == '!'){ // use ! to break the loop
break;
}else{
input = StdIn.next(); // store your input
System.out.println(input); // look at your input
}
}
}
}

Handling throws with an ArithmaticException Constructor

Question: Write a method called addTwoPositive that takes two int parameters, and if either value is not positive, throw an ArithmeticException, passing the String "Non-positive integers sent!" to the constructor of the exception. If the values are both positive, then return the sum of them.
I am confused as to how to handling this exception through the ArithmeticException constructor. Here is my code:
package IfnotPos;
public class IfNotPositive extends ArithmeticException{
public static void main(String[] args) throws ArithmeticException{
IfNotPositive pos = new IfNotPositive();
System.out.println(pos.addTwoPositive(-3,2));
}
public int addTwoPositive(int plus, int plus1) throws ArithmeticException{
if(plus < 0 || plus1 < 0){
throw new ArithmeticException("Non-positive integers sent!");
}
else{
return plus + plus1;
}
}
public ArithmeticException(String string) {
return string;
}
}
I get an error of "return type for the method is missing" and if I change it to string or anything else, it will obviously stop being a constructor. Any help handling this exception will be greatly appreciated.
First of all you don't need to extend ArithmeticException class. You are not creating a custom exception, but writing a program to throw ArithmeticException (note this resides in java.lang) if a condition is not met.
Problem with your code is that constructor you have defined is never meant to be there and is not correct, hence the compiling issue.
public ArithmeticException(String string) {
return string;
}
Just remove this constructor and you are good to go.
I don't understand why you want to create constructor for ArithmeticException in your code?
public ArithmeticException(String string) {
return string;
}
You don't write a constructor like this. This is syntax exception complaining about the above method. This constructor is unnecessary. Remove this your code will work perfect. You should see below exception running your program...
Exception in thread "main" java.lang.ArithmeticException: Non-positive
integers sent! at
com.code.samples.IfNotPositive.addTwoPositive(IfNotPositive.java:14)
at com.code.samples.IfNotPositive.main(IfNotPositive.java:8)
From Providing Constructors for Your Classes
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
I get an error of "return type for the method is missing"
You are getting this error because public ArithmeticException(String string) line in your code.
You can't add constructor of any other class inside another class, so Java treating public ArithmeticException(String string) as function rather constructor.
And as you know for method you need to have return type mendetry
You don't have to extend, ArithmeticException class. See below code:
public class IfNotPositive{
public static void main(String[] args) throws ArithmeticException{
IfNotPositive pos = new IfNotPositive();
System.out.println(pos.addTwoPositive(-3,2));
}
public int addTwoPositive(int plus, int plus1) throws ArithmeticException{
if(plus < 0 || plus1 < 0){
throw new ArithmeticException("Non-positive integers sent!");
}
else{
return plus + plus1;
}
}
}
Q: throw an ArithmeticException, passing the String "Non-positive integers sent!"
It means throw ArithmeticException with detail message "Non-positive integers sent!"
So for that you can use public ArithmeticException(String s) Constructor.
Constructs an ArithmeticException with the specified detail message.
Ex:
throw new ArithmeticException("Non-positive integers sent!");

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

Categories

Resources