Properly executing a method in a method? - java

I am trying to magically learn Java in 5 weeks because of a college class. That is not enough time to learn anything. I'm trying to complete this lab in ZyBooks, but I can't figure it out and I have no information to help. I am trying to call this checkEntry method. My results are constantly 0. Please someone explain how to do this properly.
Instructions:
Ask the user for input using the following prompt (precisely): "Please
enter a number between 15 and 45. Enter 1 to exit." Store the user's
input in a variable with the integer data type. Use a while loop to
repeat the program, checking the user's entry in case they entered a 1
to exit the program. (1) Within the loop, place the prompt (user
instructions) described above. (2) Next, within the loop, collect the
user's input and store it in a variable. (3) Finally, still within the
loop, display the output string precisely as follows, then call the
checkEntry method, passing in the variable containing the user's
input. "Output: " (do not forget the space after the colon) A separate
method called "checkEntry" has been created for you in the starting
template below (note: You can restore the default code if you wish to
start over by clicking the "Load default template…" link). Within this
method, create an IF and an ELSE, using a condition for the IF that
checks to see if the value is greater than or equal to 35. If the user
enterd a value of less than 35, the checkEntry method must multiply
that value by 5 and return the result to main(). If the user enterd a
value greater than or equal to 35, the program must instead add 10 to
their number and return the result to main().
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
int userNum;
userNum = 0;
if (userNum >= 35) {
userNum = userNum + 10;
} else {
userNum = userNum * 5;
}
return userNum;
} // do not delete this line
} // do not delete this line

Notice that your method checkEntry() never makes use of incoming; instead, it initializes userNum to 0, which means it always returns 0. It should therefore be:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
int userNum=0;
if (incoming >= 35) {
userNum = incoming + 10;
} else {
userNum = incoming * 5;
}
return userNum;
} // do not delete this line
} // do not delete this line
A simpler version would be:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
/* Type your code below this line. Create additional lines as needed. */
Scanner scnr = new Scanner(System.in);
int userNum;
userNum = 0;
while (userNum != 1) {
System.out.println("Please enter a number between 15 and 45. Enter 1 to exit.");
userNum = scnr.nextInt();
System.out.println("Output: " + checkEntry(userNum));
}
} // do not delete this line
public static int checkEntry(int incoming) {
/* Type your code for the checkEntry method below this line. Create additional lines as needed. */
if (incoming >= 35)
return incoming + 10;
return incoming*5;
} // do not delete this line
} // do not delete this line

You need to assign incoming arguments in the checkEntry method.
Replace the lines int userNum; and userNum = 0; with the following line:
int userNum = incoming;

Related

how to write Junit testing for a method that prompts the user for an int

I have a method which asks the user to choose a number between 1 and 7. It uses the Scanner class to take the users input as an int. I saw how to code this for a string, but how would I modify that for int? My method is...
/**
* This method asks the player to choose a column 1-7. If the player enters a number
outside this range
the method will continually ask until a correct number is entered. The column is
decreased by one to account for
arrays starting at 0 and returned
#param turn Player which ever players turn it is, is asked for a column
#return int the column is returned after lowered by one
*/
System.out.println("\n\n" + turn.getTag() + " please enter the column number, 1-7, \n"
+ "where you would like to drop your game piece. ");
boolean colCorrect = false;
int column = -1;
while (!colCorrect){
if(Connect4TextConsole.in.hasNextInt()){
column = Connect4TextConsole.in.nextInt();
colCorrect = true;}
else{ System.out.println("Please enter a number 1 through 7.");
Connect4TextConsole.in.next();}}
while(column < 1 || column > 7) {
System.out.println("Please enter a number 1 through 7.");
column = Connect4TextConsole.in.nextInt();
}
return column - 1; // subtract one to account for array starting at zero
}```
You don't need to test Java's API when testing your code: you can assume Scanner works (for example).
Probably the most flexible way to achieve this would be to inject a Scanner into the class handling user input and then mock that scanner in your test code:
class InputHandler {
private final Scanner input;
public InputHandler(Scanner input) {
this.input = input;
}
public void nextChoice() {
int choice = input.nextInt();
...
}
}
Then your production code would look like:
InputHandler inputHandler = new InputHandler(new Scanner(System.in));
And your test code would look like:
#Test void option2() {
Scanner input = mock(Scanner.class);
when(input.nextInt()).thenReturn(2);
InputHandler testHandler = new InputHandler(input);
...
}
#Test void illegalInput() {
Scanner input = mock(Scanner.class);
when(input.nextInt()).thenThrow(InputMismatchException.class);
InputHandler testHandler = new InputHandler(input);
...
}
If you particularly want to test that your prompts are correct then you could also inject a PrintStream for output and mock that as well:
#Test
void testChoicePrompt() {
Scanner input = mock(Scanner.class);
PrintStream output = mock(PrintStream.class);
InputHandler inputHandler = new InputHandler(input, output);
inputHandler.nextChoice();
verify(output).println("Enter choice:");
}

JAVA Method returns unexpected value

I am a very new java programmer, the below code is my first attempt at my own project. I'm certain the code is a mess, please forgive me.
In the below code the user is prompted to enter 5 values between 1 and 50.
I am placing the input values into an int[].
I want to verify that the numbers are in range so I pass the value to a method.
MY ISSUE:
If the value is in range it gets returned then the for loop increments to repeat - Good Behavior
If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value.
If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned - Good Behavior
If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array - BAD Behavior
I am certain there is something simple I am missing.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("you get 5 elements between 01 & 50:");
int a[] = new int[5];
System.out.println("\nEnter all the elements:");
for(int i = 0; i < 5;)
{
int b = in.nextInt();
a[i] = checkNum(b);
i++;
}
System.out.println("Numbers:" + Arrays.toString(a));
in.close();
}
static int checkNum(int z) {
Scanner s = new Scanner(System.in);
if (z>0 && z<51) {
return z;
} else {
System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
int qz = s.nextInt();
z = qz;
checkNum(qz);
}
return z;
}
The problem resides in your checkNum(), you are using recursion here, I don't think you know this (if you do that's great).
You need to return the checkNum(qz) value, I have simplified your logic a bit.
static int checkNum(int z) {
if (z<1 || z>50) // check for false value
{
System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
Scanner s = new Scanner(System.in);
return checkNum(s.nextInt());
}
return z;
}
You could follow a simpler approach assuming the user will input numbers and not other characters (that would throw an exception),
public static void main(String[] args) {
System.out.print("you get 5 elements between 01 & 50:");
Scanner in = new Scanner(System.in);
int a[] = new int[5];
int i = 0;
do{
System.out.println("Enter an element:");
int b = in.nextInt();
if (b > 0 && b < 51){
a[i] = b;
i++;
}else{
System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
}
}while(i < 5);
in.close();
System.out.println("Numbers:" + Arrays.toString(a));
}
Here you're asking for valid input until the threshold of 5 is reached. Because you don't know beforehand how many times the user will provide input, until the criteria are met, a do-while loop is used.

Java exception in thread "main"

I made a simple program which generates a random number between 1 to 100 and asks the user to enter a number between 1 and 100. If the number is more than the random number a message is displayed saying that it is more than the random number and if it is less it displays the opposite. The user only has 10 chances to guess the correct number. Here is the code:
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int random_num = (int) (Math.random() * 100) + 1;
System.out.println("guess a number between 1 and 100");
boolean isCorrect = false;
for (int i = 1; i <= 10; i++) {
int input = sc.nextInt();
if (input > random_num)
System.out.println("It is less than " + input);
else if (input < random_num)
System.out.println("It is more than " + input);
else {
isCorrect = true;
break;
}
}
if (isCorrect)
System.out.println("Congragulation you have guessd the correct number i.e " + random_num);
else
System.out.println("Game over it was " + random_num);
}
}
But I get errors here is the output:
guess a number between 1 and 100
It is more than 10
Exception in thread "main" java.util.NoSuchElementException
at java.base/ java.util.Scanner.throwFor(Scanner.java: 937)
at java.base/ java.util.Scanner.next(Scanner.java: 1594)
at java.base/ java.util.Scanner.nextInt(Scanner.java: 2258)
at java.base/ java.util.Scanner.nextInt(Scanner.java: 2212)
at Program.main(Program.java:15)
You are looping over the Scanner, but not checking if you have any input to fetch.
Here is an excerpt from the Java docs:
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Spot your error message ;)
Your code is valid for a standard Java environment.
However since you run the code in the SoloLearn Java container, you run into an error case that normally shouldn't happen.
Which is another thread already closed the input stream.
As Ivar already mentioned, you simply need to change your code to this to make it work on SoloLearn without errors:
for (int i = 1; i <= 10 && sc.hasNextInt(); i++) {
// Your logic
}
But since SoloLearn's implementation needs you to feed all of your input at once (different inputs seperated by a line break), you won't be able to run this correctly with different guesses.
SoloLearn will take those inputs, seperated by line breaks, and reads the different lines one at a time.
Then returns the inputs one at a time to your program.
Once it has no more input, it will close the stream.
However your program still tries to read this stream and then gets a java.util.NoSuchElementException error.
Here is reproducable code of the error with wath I believe happens behind the scenes at SoloLearn:
import java.io.ByteArrayInputStream;
import java.util.Scanner;
public class Program {
private String[] userInput;
private int inputNumber;
public Program(String input) {
this.userInput = input.split(" ");
this.inputNumber = 0;
}
public void startGame() {
int random_num = (int)(Math.random()*100)+1;
System.out.println("Guess the number between 1 and 100!");
boolean isCorrect = false;
for (int i = 1; i <= 10; i++) {
System.out.print("Guess "+ i +": ");
int input = getInput();
if (input > random_num)
System.out.println("It is less than " + input);
else if (input < random_num)
System.out.println("It is more than " + input);
else {
isCorrect = true;
break;
}
}
if(isCorrect)
System.out.println("Congratulations, you have guessed the correct number i.e " + random_num);
else
System.out.println("Game over! The number was " + random_num);
}
private int getInput() {
if (inputNumber < userInput.length)
fakeUserInput();
Scanner sc = new Scanner(System.in);
int input = -1;
input = sc.nextInt();
if (inputNumber == userInput.length)
sc.close();
return input;
}
private void fakeUserInput() {
System.setIn(new ByteArrayInputStream(userInput[inputNumber].getBytes()));
inputNumber++;
}
public static void main(String[] args) {
Program p = new Program("10 20 30");
p.startGame();
}
}
We feed it 3 guesses: 10, 20 and 30
And this is the output:
Guess the number between 1 and 100!
Guess 1: It is more than 10
Guess 2: It is more than 20
Guess 3: It is more than 30
Guess 4: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:873)
at java.util.Scanner.next(Scanner.java:1496)
at java.util.Scanner.nextInt(Scanner.java:2128)
at java.util.Scanner.nextInt(Scanner.java:2087)
at Program.getInput(Program.java:47)
at Program.startGame(Program.java:24)
at Program.main(Program.java:62)
As you can see, once the inputs are depleted and the stream is closed, we get this error.
I hope this explains your problem and sheds some light on the WHY.
here is answer, I try to do it and I found in main sc.close(). After comment line all work nice! :
#I_code Is this the actual code you are using? It works fine for me. That error is thrown when the the System.in is closed. Are you using sc.close() somewhere that you didn't show in the code?
– #Ivar Mar 15 '19 at 10:10
Good morning you need to initialize the input variable outside the for like this:
int input;
for (int i = 1; i <= 10; i++) {
input = sc.nextInt();
if (input > random_num)
Try this and tell me

Calling a method that displays the output pattern only

I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.

Program to decide whether second number is a multiple of the first not working properly

This program should be returning True if the second number is a multiple of the first. False if it is not, and it should do it three times.
The output is just giving whatever answer is correct for the first one.
How can I get the return to include the variables f, and g?
Or if that is not the correct way to go about it what is? I need to have them all come from the same method, otherwise I'd just make more methods, but as it is I'm stumped.
Any help is greatly appreciated. Sorry for my noobiness.
import java.util.Scanner;
public class Numbers3 {
// starts execution of java application
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstnumber = 0; // initialize integer first number
int secondnumber = 0; // initialize integer second number
int third = 0;
int fourth = 0;
int fifth = 0;
int sixth = 0;
// First input field
System.out.print("Input first number ");
firstnumber = input.nextInt();
// Second input field
System.out.print("Input second number ");
secondnumber = input.nextInt();
// makes result equal the Boolean output of isMultiple method
Boolean result = isMultiple(firstnumber, secondnumber, third, fourth,
fifth, sixth);
System.out.println("" + result);
System.out.println();
System.out.print("input first number ");
third = input.nextInt();
System.out.print("input second number ");
fourth = input.nextInt();
System.out.println("" + result);
System.out.println();
System.out.print("input first number ");
fifth = input.nextInt();
System.out.print("input second number ");
sixth = input.nextInt();
System.out.println("" + result);
}
// creates method using the user input
public static Boolean isMultiple(int a, int b, int w, int x, int y, int z) {
Boolean e = null; // initialize boolean
Boolean f = null;
Boolean g = null;
if (a % b != 0) // what the function does if the result is not 0
e = false;
// what the function will do if the function does result in 0
if (a % b == 0)
e = true;
if (w % x != 0)
f = false;
if (w % x == 0)
f = true;
if (y % z != 0)
g = false;
if (y % z == 0)
g = true;
return e;
// returns e as the result of this method.
} // end program
} // end class
For every run, there's two inputs.
Objective: Check if the first input is a multiple of the second input using isMultiple().
To run it 3 (or any #) times, put the repeating code in a for loop.
# of times to repeat the loop is stored in the constant NUM_RUNS.
Code:
import java.util.Scanner;
public class Numbers3 {
private static final int NUM_RUNS = 3;
// starts execution of java application
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < NUM_RUNS; i++) {
// First input field
System.out.print("Input first number: ");
int firstNumber = input.nextInt();
// Second input field
System.out.print("Input second number: ");
int secondNumber = input.nextInt();
System.out.printf("%d is a multiple of %d: %s%n%n",
firstNumber, secondNumber,
isMultiple(firstNumber, secondNumber));
}
}
public static boolean isMultiple(int a, int b) {
return (a % b == 0);
}
} // end class
Example Input/Output:
Input first number: 8
Input second number: 2
8 is a multiple of 2: true
Input first number: 7
Input second number: 3
7 is a multiple of 3: false
Input first number: 18
Input second number: 6
18 is a multiple of 6: true
I'm not sure what's with f and g, but here's a program that asks for two numbers, three times, and prints true or false if the second is a multiple of the first:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 3; i++) {
System.out.print("Enter first number : ");
int first = Integer.parseInt(reader.
System.out.print("Enter second number : ");
int second = Integer.parseInt(reader.readLine());
boolean secondMultipleOfFirst = second % first == 0;
System.out.println(secondMultipleOfFirst);
}
}
And I know what's wrong with your method, as well. You are calculating the values correctly, but every time you are returning e, which is the first result. So, the next two inputs give the first result.
Instead of setting up more methods, or a way to see which value to return, use a loop. That way, you take two values and see if n2 is a multiple of n1.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dump_me;
import java.util.Scanner;
public class Numbers3
{
// starts execution of java application
public static void main( String[] args)
{
Scanner input = new Scanner (System.in );
int firstnumber = 0; // initialize integer first number
int secondnumber = 0; // initialize integer second number
// makes result equal the Boolean output of isMultiple method
String loop = "N";
do{
// First input field
System.out.print("Input first number ");
firstnumber = input.nextInt();
// Second input field
System.out.print("Input second number ");
secondnumber = input.nextInt();
Boolean result = isMultiple(firstnumber, secondnumber);
System.out.println("" + result );
System.out.println();
System.out.println("Do you wan to continue? Press y to continue or n to exit" );
loop = input.next();
}while(loop.equalsIgnoreCase("y"));
}
// creates method using the user input
public static Boolean isMultiple( int a, int b)
{
if(a==0 || b==0)
{
return false;
}
else
{
if(b % a ==0)
{
return true;
}
else
{
return false;
}
}
// returns e as the result of this method.
} // end program
} // end class
User input have been put in the loop. This program will accept the user input and check the values.

Categories

Resources