This question already has an answer here:
Missing return statement error in a method
(1 answer)
Closed 9 years ago.
trying to figure this out. I've created a method that checks if the user has entered an integer using a catch block.
The method obviously is asking for a return statement but no matter where I put it it does not work. Could anyone offer any advice?
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
inputDouble();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn == true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {System.out.println ("Integers only, try again" );
myKeyboard.next();
return num;
}
}
}
}
When carryOn == false then it will go to the bottom of your method and there's no return statement there. You need to have a return statement at the bottom.
Here's an explanation of the error: If a function says it returns something (an int in this case) that means that every path it can take must return an int. You're missing one of those paths which is a compile time error.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Looking for some help here. I'm trying to make this method work. Whenever I run the method, it throws IllegalArgumentException even if I do type in A,B,C or D. I am using an inputReader class. Here is the code for my DriverExam class. Please let me know where I am going wrong. I'd like it so the only valid answers are a,b,c,or d. I have to use a while loop and everything I've tried won't help me match the driverAnswers.
public class DriverExam
{
// instance variables
public static final String[] ANSWERS = {"B","D","A","A","C","A","B","A","C","D","B","C","D","A","D","C","C","B","D","A"};
private String [] driverAnswers;
private InputReader inputReader;
public DriverExam(){
driverAnswers = new String[20];
inputReader = new InputReader();
}
public void promptStudentAnswers(){
int index = 0;
while(index < driverAnswers.length){
System.out.println("enter answer");
String driverAnswers = inputReader.readString();
if(driverAnswers != ANSWERS[index]){
throw new IllegalArgumentException(" answers can only be A,B,C or D");
} else{
index++;
}
}
}
}
First, you want to test if the answer is one of A, B, C or D (not that the answer matches something in the correct answers array). Also, your driverAnswers is masked because you created another local variable with that name. Basically, I think you wanted something like
public void promptStudentAnswers() {
int index = 0;
while (index < driverAnswers.length) {
System.out.println("enter answer");
String answer = inputReader.readString().trim().toUpperCase();
if (answer.length() == 1 && "ABCD".indexOf(answer) != -1) {
driverAnswers[index] = answer;
index++;
} else {
System.out.println("Answers can only be A,B,C or D");
}
}
}
I know this has been asked before, but not in a way I understood, because I am dumb.
So.
I need to take some variables into a class, compare them against something, and then return the higher of the two. In the long run, I need to compare against a running total, but for my problem, I think the issue is considerably more fundamental. I'm not understanding how to pass a variable BACK to my main class.
import java.io.*;
public class testing123 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass();
System.out.println("Your numbers combined is " +numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
public static Integer testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
numbersCombined = numbersCombined;
}
else {
numbersCombined = 100;
}
System.out.println(numbersCombined);
return numbersCombined;
}
}
If I remove the return, this will print the numbersCombined, but that's all it does. With the return in place, it doesn't execute the print line above the return, and first prints the original numbersCombined (which it shouldn't if you use, say, 10 and 20, since that's less than 100), and then prints testClass#76046e53 rather than the actual value. I know there's a way to override it, but the answers I've found don't work for me.
I know this answer: http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F29140402%2Fhow-do-i-print-my-java-object-without-getting-sometype2f92e0f4&sa=D&sntz=1&usg=AFQjCNGIzxlBSH8xIS7hurKe6_Euc7B8RQ
is the basic problem I'm encountering, but the overrides listed aren't really working for me, and I want integer anyway, rather than string.
In the end, what I'm "really" doing is taking a series of 4 numbers from a user, then using this function to compare whether THIS series of numbers is higher than the previous maximum, and if it is, that's the new maximum moving forward, with a loop until the user is done entering serieses of 4 numbers, and then finally printing the maximum.
I was able to write this without ANY functions, all inline, easy as pie. But once I send the comparison to a function, I don't understand how to send it back, and I've spent all day trying to understand the concept. ALL DAY. So, while I know it's going to be a stupid answer, that's because I'm stupid, but not because I didn't try (sorry, kind of defensive. Frustrated).
Fundamentally, I want to send two (this example is just one) variables to a class, compare them, change ONE of them, and return it to the main class. In this example, I'm just trying to send ONE variable, compare it, and the send it back.
You need to call the method within TestClass. Your code is already returning an integer from that method.
Once you instantiate the class run testClass.testClass(numbers)
The way you're throwing around pseudo-global variables between classes is probably the problem. Pass them through the calls like above, rather than implicitly.
Try to do something like this:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass(numbersCombined); // constructor should be like this
System.out.println("Your numbers combined is " + numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
Integer numbersCombined;
// This is a constructor
public testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
this.numbersCombined = numbersCombined; // use this to represent the object
} else {
this.numbersCombined = 100;
}
System.out.println(numbersCombined);
}
// Add method toString()
public String toString() {
return this.numbersCombined.toString();
}
}
This question already has answers here:
Java exception handling
(8 answers)
Closed 7 years ago.
Well im really new to java and im really trying hard to understand what can be done in java and what can't. I'm making a console application based on the well known game Hangman. Basiclay what i'am trying to do is stop the user from typing 'e's more than twice, to do that i made 2 methods:
The first one adds 1 to the int variable mManyTimes whenever the user types e.
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
the second method is the one that sends an exception
to the user when the user types e more then twice.
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
Basicly i created two files, one that holds the code of the game(Which those two methods are in) and other one.
the file that holds the logic of the game is Game.java and here is the code that is inside it:
public class Game {
private String mAnswer;
private String mHits;
private String mMisses;
private int mManyTimes;
public char letter;
public Game(String answer) {
mAnswer = answer;
mHits = "";
mMisses = "";
}
public boolean applyGuess(char letter) {
//checks for char letter inside the mAnswer variable.
//If it is there the indexOf() method should return the index of the letter.
//If it is not there it will return -1.
//We are basicly saing if indexOf() method returns 0 or more then that then the isHit
//if it is not then the isHit boolean will return false.
boolean isHit = mAnswer.indexOf(letter) >= 0;
if (isHit) {
mHits = mHits + letter;
} else {
mMisses = mMisses + letter;
}
adder();
return isHit;
}
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
The other file that holds the main() method and prints the code to the console is Hangman.java:
public class Hangman {
public static void main(String[] args) {
// Enter amazing code here:
Game game = new Game("treehouse");
game.applyGuess('e');
game.applyGuess('e');
System.out.println(game.cheatStopper());
}
}
So here is the question that frustrated me and i never found and answer for:
How do i get my code to work and stop the user from typing more then two e.
Well well i know my code has many errors and bad structure but dont forget that im new to java, and thanks for advance :).
You need a catch block. Look up how to catch exceptions.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been trying to get this code to work for the past week now, and every time I make one change I end up with more bugs. Can anyone help figure out where I've gone wrong?
The code is split up into two files: a runner class, and a class with all the methods.
import java.util.Scanner;
import static java.lang.System.*;
public class RPSRunner
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String response = "";
String player = "";
RockPaperScissors game = new RockPaperScissors();
System.out.print("What is your name? : ");
player = keyboard.next();
out.print("type in your prompt [R,P,S] :: ");
response = keyboard.next();
game.setPlayers();
game.convertUserInput(response);
game.setPlayerChoice(response);
game.computerThink();
game.determineWinner();
}
}
The method class:
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Random;
public class RockPaperScissors
{
private String playerName; //used to set player's name
private int playChoice; //player's choice as a number
private int compChoice; //computer's choice as a number
private int playerNumber;
Random rand = new Random(); //allows useage of random methods
public RockPaperScissors()
{
//sets everything to null, prepare for incoming calculations
playerName = "";
}
public RockPaperScissors(String player)
{
playerName = player;
}
public void setPlayers(String player)
{
//good ol mutator method
playerName = player;
}
public String convertUserInput(String response)
{
//Convert R, P, S to integer using switch case
//If invalid input, set to -1
switch(response) {
case "R": playChoice = 0;
break;
case "P": playChoice = 1;
break;
case "S": playChoice = 2;
break;
default: playChoice = -1;
}
}
public boolean setPlayerChoice(String response)
{
//TODO set playChoice to convertUserInput
//return (playChoice != -1)
playChoice = convertUserInput(response);
return(playChoice != -1);
}
public int computerThink()
{
//Use Math.random from 0-2 inclusive
//return it all in one statement so
//return Math.random(whatever);
return rand.nextint(2);
}
public String determineWinner()
{
String winner="";
compChoice = computerThink();
switch(compChoice) {
case 0:
if(playChoice == 1){
winner = playerName;
} else if(playChoice == 2) {
winner = "Computer";
} else if(playChoice == 0) {
winner = "Tie";
}
case 1:
if(playChoice == 1) {
winner = "Tie";
} else if(playChoice == 2) {
winner = playerName;
} else if(playChoice == 0) {
winner = "Computer";
}
case 2:
if(playChoice == 1) {
winner = "Computer";
} else if(playChoice == 2) {
winner = "Tie";
} else if(playChoice == 0){
winner = playerName;
}
} //closes the switch
return winner;
}
}
This is my first major program, so I apologize for any glaring errors or incorrectly-interpreted concepts. I think my major issue lies in the return types, but I'm not positive.
Looking through your code, it is a bit of a mess, so I'll go through step by step.
game.setPlayers();
game.convertUserInput(response);
game.setPlayerChoice(response);
game.computerThink();
game.determineWinner();
You call ALL of these, yet some have return types and are called in previous functions already. For example, convertUserInput.
Your convertUserInput function sets the playChoice variable, declares it returns a String but actually returns nothing. This is called with your clump of functions above, but is then also called by setPlayerChoice, which replaces the playChoice set in the call with, well, nothing. Because nothing is returned you get a compile error.
computerThink returns an int, but you call it above without setting the returned value to anything, then determineWinner is called, which WOULD work had it not been for the above problems.
There is quite a bit wrong with your code. A few obvious ones: you have parameterized your setPlayers method of the RockPaperScissors class to accept a string, but when you invoke it, you dont provide any value, thats a compile time issue. In the RockPaperScissors class you have a method convertUserInput whose method signature says it will return a string, but there are no code paths which return a value in that method. I would do a few more simple tutorials to try to wrap your head around basic OOP concepts then come back to this once you understand basic stuff like, What is an Object? What is a method signature? and most importantly, read and interpret the compile time errors.
It's a little strange that you know your problem lies with the return types but don't know how to fix it. Are you just reading the error message but don't know what its actually saying?
The return type is declared in the first line of a method, the method declaration. The method is expected to return the return type or you will receive a compile-time error.
Some Examples
//these are method declarations
// the return type is before the name of the method
public void setPlayers(String player) {} //return type "void" - this method should not return anything
public String convertUserInput(String response) { // return type "String" - this method NEEDS to return a String
return "A String";
}
Matching method calls
//You need to match the return type with how you call the method
String myPlayers = setPlayers("player"); //WON'T COMPILE - setPlayers returns void, not String
setPlayers("player"); // this is okay, nothing is returned, return type void
String convertedInput = convertUserInput("response"); // this is okay, return type String, which is what convertedInput will be.
convertUserInput("response"); // this is also okay, even though it returns a String we don't have to assign it to a variable. Though in this example calling the method like this is pretty much useless.
int convertedInput = convertUserInput("response"); //WON'T COMPILE - convertUserInput returns String, not an int.
I'm trying to put a try-catch into a procedure type method but I'm 95% sure it has to be a function type. What I'm trying to accomplish is to make my code shorter in the main. One of the biggest things I thought of was to put a try-catch into a method and call the method.
The thing is, it will validate the input if it is a integer or not- it even catches the exceptions the problem is that it doesn't "remember" the validated input once it continues on with the program/calculates. Here's the part of the code I'm having trouble with.
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
And here is the entire program:
import java.util.Scanner;
public class ch7exercise1
{
public static double compound(double oA, double cI)
{
return roundCent((oA*(Math.pow((1+(percent(cI))),10))));
}
public static double percent(double interest)
{
return interest/100.0;
}
public static double roundCent(double amount)
{
return ((Math.round(amount*100))/100.0); //100.0 is mandatory.
}
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args)
{
boolean f = true;
boolean f2 = true;
double origAmount = 0;
double compInterest = 0;
double total = 0;
Scanner iConsole = new Scanner(System.in);
System.out.println("10 year Compound Interest Claculator\n");
System.out.println("Input amount of money deposited in the bank");
tryCatchNum(origAmount);
System.out.println("Input compouded interest rate. (If the compound interest is 3% input 3)");
tryCatchNum(compInterest);
total = compound(origAmount,compInterest);
System.out.println("$"+total);
}
}
Java arguments are passed by value. You're passing 0 to the tryCatchNum method. A copy of the value is passed to the method. This method assigns a new value to its own copy, and then returns. So the original value is still 0.
You must not pass anything to the method. Instead, the method must return the value it has validated. Also, consider using a more appropriate method name:
public double readDoubleValue() {
...
return value;
}
And in the main method:
double origAmount = readDoubleValue();
Since double is a primitive in Java it is passed by value to the method, therefore when you alter the value of the primitive the changes to the method parameter are not reflected in the original variable passed into the method call.
Read the cup story on Java ranch which explains pass by value and pass by reference.
http://www.javaranch.com/campfire/StoryCups.jsp
The next story to read is the Pass By Value story on Java Ranch.
http://www.javaranch.com/campfire/StoryPassBy.jsp
You should alter your method so that it returns a double which is assigned to value in the main method of your program.
I am also very curious as to why you are using a while loop that checks true. I think it is highly likely your program will encounter an infinite loop if the value entered cannot be converted to a double.