Errors with missing return statement - java

Every time i try to compile my code i get a error about a missing return statement. Any ideas about whats wrong with my code?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
So i fixed a couple of things, but now im getting an error where my variable 'result' might not have been initialized, any suggestions?
import javax.swing.JOptionPane;
import java.io.*;
public class facts
{
public static void main(String[]args)
{
String input;
int x;
char y,prime,perfect;
do{
input = JOptionPane.showInputDialog("Enter an integer");
x = Integer.parseInt(input);
if(x%2==0)
System.out.println("The integer is even - it is evenly divisible by 2");
else
System.out.println("The integer is not even - it is not evenly divisible by 2");
prime = isPrime(x);
if(prime == 't')
System.out.println("The integer is a prime number");
else
System.out.println("The integer is not a prime number");
perfect = isPerfect(x);
if(perfect == 't')
System.out.println("The integer is a perfect number");
else
System.out.println("The integer is not a perfect number");
input = JOptionPane.showInputDialog("Enter Y for another number, anything else to quit");
y = input.charAt(0);
}while(y=='Y');
System.out.println("Good Bye");
System.exit(0);
}
public static char isPrime(int x)
{
for(int y=2;y<x;y++)
{
if(x%y==0)
return 't';
else
return 'f';
}
}
public static char isPerfect(int x)
public static int triAng(int x)
{
int result,z,y = 1;
while(y<=x)
{
z=y*(y+1)/2;
y++;
System.out.println(z);
result = z;
}
return result;
}

You need to put return statements after your for loops and return a default char or null, in case the loops would not be entered. And in your isPerfect, even the if may not be entered.
For your variable 'result' might not have been initialized problem, the problem is that line:
int result,z,y = 1;
only the y variable is initialized to 1. As you might not enter the while loop, then the return statement would return result with it not having been initialized, so you need to explicitly specify a value to it (null or whatever integer).
If you want them all to be 1 you can do:
int result,z,y;
result = z = y = 1;

in your isPerfect method, you don't have a return statement for the case that the code does not enter if if(x%y==0) block.

For example, this code might not return if x <= 1 or if x%y is never 0:
public static char isPerfect(int x)
{
int y,z=0;
for(y=1;y<x;y++)
{
if(x%y==0)
{
z+=y;
if(z==x)
return 't';
else
return 'f';
}
}
}

In the isPrime and isPerfect methods, your code may not enter in the for loop. To adjust it, put a default return on the end of these methods or throw an exception.

Related

Java Exception handling looping error

I FIGURED EVERYTHING OUT TY FOR THE HELP
When I type in letters at attempt 1/4 it works fine and it continues, but once I type a letter at attempt 2/4 it just prints the message and the program stops. Also any tips on #2, I can only think of if(guess>=4 && guess<=16) else statement(not sure if this is correct)
When I execute the code -
Guess a number between 1 and 16.
Attempt 1 of 4: 8
You guessed 8
Too Low!
Attempt 2 of 4: a
Please enter an integer between 4-16
can't enter anything after
Problems: I have to make exception handlers if user types in a
1) non-numeric input
2) out of range input
3) Have to retain current guess amount
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
static final int limit = 4;
static final int maxInteger = 16;
public static void main(String[] args) {
Random rand = new Random();
int target = rand.nextInt(maxInteger) + 1;
int x = 1;
do{
try{
Scanner input = new Scanner(System.in);
System.out.printf("Guess a number between 1 and %d.\n", maxInteger);
int attempts = 1;
while (attempts <= limit) {
System.out.printf("Attempt %d of %d: ", attempts, limit);
int guess = input.nextInt();
System.out.printf("You guessed %d\n", guess);
if(guess > target) {
System.out.printf("Too High! \n");
}
else if(guess == target){
System.out.printf("The answer is %d, You win!", guess);
attempts = 20;
}
else{
System.out.printf("Too Low! \n");
}
attempts+=1;
x = 2;
}
if(attempts==5){
System.out.println("You lose!");
}
}
catch(InputMismatchException e){
System.out.printf("Please enter an integer between 4-16");
continue;
}
}while(x == 1);
}
}
You are checking while(x == 1); in the outer loop and from the inner loop you incremented the value of x by doing x = 2;. This will break the condition and you'll come out of the outer while loop.
You should be setting a valid condition for the outer while loop if you want to continue. Try something like while(x < 5);
Your code should look something like this:
do {
try {
...
/* Inner While */
while() {}
...
} catch () {
/* Exception Handling */
...
}
} while(x < 5); /* Decide a valid condition */
1) try moving your try catch block inside the inner loop so it only encloses
int guess = input.nextInt();
2) your idea for number 2 should work.
if(guess>=4 && guess<=16)
make sure this is the first if statement in your checks, then you don't have to change any of your other if statements.
3) make a variable outside both of the loops called guess, then instead of saying
int guess = input.nextInt();
just say
guess = input.nextInt();
The current guess wil be availble to you until you update it.
4) your variable x is confusing. Are you using it as a flag to end the outer loop? if that is the case make it a boolean
boolean flag = true;
then you can set the flag to false when you are ready to break out of the loop. change
x = 2;
to
flag = false;
also for the loop all change
while(x==1)
to
while(flag)

Get user input of positive integers in java

I have to write a program which asks a user to input integers, but they have to be positive.
I'm pretty sure I have to use a loop, and don't think I'm allowed to use Math.abs().
What I've written right now looks quite messy though. Here is the code:
public class Q1{
public static void main(String[] args){
int num1, num2, num3;
while(true){
System.out.println("Input first integer.");
num1 = TextIO.getInt();
if(num1 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input second integer.");
num2 = TextIO.getInt();
if(num2 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input third integer.");
num3 = TextIO.getInt();
if(num3 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
....
}
}
I've basically just done separate while loops for each integer to test if the integer is positive because when I use one loop I can't get it to run properly. Is there a way of just using one loop that will still work but looks much neater?
You can move that loop inside another method:
public int readPositiveInt() {
int num = 0;
int attempt = 0;
int maxAttempt = 3;
// Allow only maxAttempt to enter correct input.
while(true && attempt < maxAttempt) {
num = TextIO.getInt();
if(num > 0)
break;
System.out.println("Integer isn't positive. Try again");
++attempt;
}
return num;
}
And then call this method where ever you are having a loop currently.
Make sure TextIO, whatever it is, is available to this method.
Also, you should better enforce a maximum number of attempt, as you might go into an infinite loop, if user keeps on entering negative numbers.
You can wrap your while loop inside a for loop and put your integers in an array:
int[] nums = new int[] {-1, -1, -1};
for (int i = 0; i < 3; i++) {
while(nums[i] <= 0)
nums[i] = TextIO.getInt();
}
When programming you try and achieve 3 objectives: making your code, readable, intuitive and maintainable.
I would suggest you create a method you can reuse. The method in your case would look something like this:
public int readPositiveInt(String message) {
int num = 0;
boolean exitLoop = false;
while(!exitLoop){
System.out.println(message);
num = TextIO.getInt();
if(num > 0) {
exitLoop = true;
// I don't like to break from a while(true), I personally find it messy
}
else {
System.out.println("Integer isn't positive. Try again");
}
}
return num;
}
Instead of creating variables like, num1, num2, num3 ... simply create an int array and store all values in there. If you are not sure how many numbers you would like to store, I suggest you use an implementation of a List, like the ArrayList.
I hope this helps.
Something like this perhaps?
public class Q1{
public static void main(String[] args){
int[] input_integers = new int[3]; //create an array of however many integers you need
int i = 0; // initiate your counter
while(i<input_integers.length){ // you will loop through until all integers are set
System.out.println("Input integer number "+ (1+i)); // computers count from 0, humans from 1
input_integers[i] = TextIO.getInt();
if(input_integers[i] < 0) // check if it is not positive
System.out.println("Integer isn't positive. Try again");
else { // if it is, increment your counter and get the next integer
i++;
}
}
}
}
Hope this helps
** This code was not tested
Here is a solution with a single while loop and using no array(it can be done). But, you can see that it's not upto the expectation. Such an implementation is always inefficient and is discouraged. So better use an array or separate method like others are suggesting.
int i=0;
while (i < 3) {
int tmp = 0;
switch (i) {
case 0:
num1 = tmp = TextIO.getInt();
System.out.println("Input first integer.");
break;
case 1:
num2 = tmp = TextIO.getInt();
System.out.println("Input second integer.");
break;
case 2:
num3 = tmp = TextIO.getInt();
System.out.println("Input Third integer.");
break;
}
if (tmp < 0) {
System.out.println("Integer isn't positive. Try again");
} else {
i++;
}
}

Need help making a random math generator

What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();

Determine prime number by user input using recursive method

I need to create a program in Java that determines if a number is prime.
The user should enter any number, and the program will determine if it's prime or not, and display "not prime" or "prime." My code now compiles and runs but it always says a number isn't prime even if it is.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int constant = 0;
int variable = 0;
System.out.println("Enter a Number to test if Prime or Not");
constant = input.nextInt();
variable = constant;
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println(+answer);
if (answer == 1)
{
System.out.println(+constant + " is a prime number.");
}
else
{
System.out.println(+constant + " is NOT a prime number.");
}
}
public static double testPrime(int number, int divide)
{
double prime = 0.0;
prime = number%divide;
if (prime > 0 && divide != number)
{
return testPrime(number, divide - 1);
}
else
{
return prime;
}
}
}
if (prime > 0 && divide != number)
This will never be true. Because your divide and number are always equal.
See that you have assigned variable=constant and that's what you pass to the method
constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);
That said, you need go so complex to find out if a number is prime or not. Check the web for simple algorithms. See http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/ for example.
Not the answer as the OP wants recursion (homework I guess).
You need to only go till the square root of n to see if it has a divisor (divisor besides self will be < sqrt(n))
boolean isPrime(int n) {
if(n % 2 == 0)return false;
int till = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
for(int i= 3;i<till;i+=2) {
if(n % i == 0)
return false;
}
return true;
}
I see you want recursion for this, so I converted tgkprog's answer to a recursive method (although his is definitely more efficient). Additionally, I think you may want to return a prime factor if the input isn't prime? I'm just speculating this judging from the OP's return value of a double instead of a boolean. Mine will return an int though, because returning a double is silly.
int isPrime(int n){ //starter function
if(n<=1) return n; //sanity check for weird inputs
if(n % 2 == 0) return 2; //2 is a prime factor
int start = (int)java.lang.Math.pow(n, 0.5);
return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}
int isPrime(int n, int testval){ //recursive function
if(testval<=1) return 1; //n is prime, return n since it has no prime factors
if(n % i == 0)
return i; //found a prime factor!
return isPrime(n,i-2);
}
with recursion
import java.util.Scanner;
public class PrimeRecursion
{
static int dbg;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter non 0 if you want debug :");
dbg = input.nextInt();
long constant = 3;
long variable = 0;
while(true){
System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
constant = input.nextLong();
if(constant < 3){
if(constant == 2){
System.out.println("2 is a special prime");
}
return;
}
if(constant % 2 == 0){
System.out.println(constant + " is NOT a prime number, even number.");
}else{
variable = (long)Math.pow(constant, 0.5);
variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println("End answer : " + answer);
if (answer == 1){
System.out.println(+constant + " is a prime number. answer : " + answer);
}
else{
System.out.println(constant + " is NOT a prime number.answer : " + answer);
}
}
System.out.println();
}
}
static double testPrime(long number, long divide)
{
double prime = 0.0;
prime = (double)number / divide;
if(dbg > 0){
System.out.println("Debug number " + number + " | divide " + divide + " |prime : " + prime + " | Math.abs(prime) " + Math.abs(prime));
}
if (prime == ((long)prime))//whats the best way to do this?
{
//divided evenly
return divide;
}
else{
return testPrime(number, divide - 2);
}
}
}
the recursive function for me goes like-Correct me if i am wrong.Thank you.calling statement >Boolean b=isPrime(number,number-1);
recursive function-
void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}
Well I am directly giving you all the code instead of writing snippet. Hope you all may like this one as I have tried my best to make it as simple as possible.
The code is :>
import java.util.*;
class Prime_Number
{
static int c=0;
public static void main(String args[])
{
int n,i,sq=0;
Scanner in=new Scanner(System.in);
Prime_Number ob=new Prime_Number();
System.out.print("Enter a no.:>");
n=in.nextInt();
i=n;
sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
int k=ob.prime_Chk(n,i,sq);
if(k==1)
{
System.out.println("Prime");
}
else
{
System.out.println("Non-Prime");
}
}
public int prime_Chk(int g,int i,int sq)
{
if(i==sq)
{
return c;
}
else
{
if(g%i==0)
{
c++;
}
i--;
return(prime_Chk(g,i,sq));
}
}
}
Well in the prime() I have taken int i , int sq and int g as arguments.Instead of those if you wish then you can take other variables also.
import java.util.Scanner;
public class HW8R_T03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int n = sc.nextInt();
int simple = prime(n,n-1);
System.out.println(simple==1 ? "prime" : "not prime");
}
static int prime(int x, int y){
int div = 1;
if (y==0 || y==1){
return div;
}
if (x%y==0){
div = y;
} else {
div = prime (x, --y);
}
return div;
}
}

Missing return error

/**
* Read a positive integer and return its value
* #param the prompt to be shown to the user
*/
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
}
I'm trying to make it so the user can't insert 0 or a negative number. However I don't think my logic is correct as I'm getting a missing return error. Can anyone help?
Thanks!
The if should be a while:
while (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
Really, there's no need of keeping the positive boolean, since the moment it passes
if (input > 0)
it immediately returns, without any further checks on the boolean.
Your method signature is as follows:
public static int readPositiveInteger(String prompt)
However, you never return an integer. You have two choices:
Add something like return 0; to the end of your method
Change static int to static void.
The first is the better option, I think, since you want to return the integer that was read. If none is read, you can tell the program a 0 was there.
The best option, though, is to modify your if statement to use a while loop, and return something only when the user has inputted something.
As mentioned by others here, your outer if statement should be a while loop:
while (scan.hasNextInt() && positive == false)
{
...
}
Also, you've only one return statement written in an if statement. If simply converting the above mentioned if statement to a while loop doesn't help, try return 0 after your while loop.
The java compiler (and others as well) doesn't understand the semantics of code. It can only check for a correct syntax. So, in your case, it might be concerned that the return command might never be reached. A return 0 at the end of your function would solve that (despite that return 0 will never be reached).
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
int input;
if (scan.hasNextInt() && positive == false)
{
input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return input;
}
All paths of your method should return something since you define it as
public static int readPositiveInteger(String prompt)
Looks like you are expecting your code to be in a while loop or something?
As it stands it can "run off the bottom" - and like the error says, there is no return (which is required).
You need a while loop. In pseudo code:
While true (ie loop forever)
Ask for input
If input ok return it
You have to add a return statement in the else block otherwise your code wont compile
your method expects a return statement in the else block
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
return 0;//your missing return statement
}
}
What you have to do is add return input; in the end of the method that is
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false) {
int input = scan.nextInt();
if (input > 0) {
positive = true;
{
return input;
}
} else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return 0;
}
This function will work perfectly for you
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
System.out.println("Enter an integer");
Scanner scan = new Scanner(System.in);
boolean positive = false;
int input = 0;
while (input <= 0) {
System.out.println("please enter a number greater then 0");
input = scan.nextInt();
}
return input;
}
public static int readPositiveInteger()
{
return int_type;
}
has the return type as int so you should return the integer values in function.

Categories

Resources