Java - Method structure execution - java

I am going through the University of Helsinki's Java course and I have a question on one of the examples.
The code in question:
import java.util.Scanner;
public class UserInterface {
private Scanner reader;
public UserInterface(Scanner reader) {
this.reader = reader;
}
public void start() {
while (true) {
String command = reader.nextLine();
if (command.equals("end")) {
break;
} else {
handleCommand(command);
}
}
}
public void handleCommand(String command) {
if (command.equals("buy")) {
String input = readInput("What to buy: ");
System.out.println("Bought!");
} else if (command.equals("sell")) {
String input = readInput("What to sell: ");
System.out.println("Sold!");
}
}
public String readInput(String question) {
while (true) {
System.out.print(question);
String line = reader.nextLine();
if (line.equals("carrot")) {
return line;
} else {
System.out.println("Item not found!");
}
}
}
}
If you choose to buy or sell something that isn't a carrot why does it not run the line directly below the input line in the handleCommand method (printing Bought! or Sold!)? I don't understand how it terminates the conditional in the case that a carrot is not bought or sold. How is the readInput method manipulating the handleCommand method here? Thanks.

The function readInput() is rather oddly defined: it will only return if you enter carrot.
readInput() contains a while loop that keeps looping until the user enters carrot, otherwise it says Item not found! and tries again. The output lines in handleCommand() are only executed when readInput() returns.

Basically your readInput() method returns the String "line" only if the user inputs "carrot" otherwise it will keep on going inside the else part and continue printing "Item not found!". But instead of System.out.println("Item not found!") ,
if you just return that statement then either "carrot" or "Item not found!" will be returned and stored in the "input" variable of handleCommand() method. In that case now it will print your "Bought!" or "Sold!" print statement irrespective whether you choose "carrot" or something else

Related

Java JUnit: test for user input (pass standard input to Scanner)

Issue: I'm trying to test a simple program in Java that requires user input but while I'm able to feed the input to the test, I'm only able to do so in the first called method. The error thrown is java.util.NoSuchElementException: No line found
The setup: The first method ask for user to type a command, after that and depending on the command the method will call on other methods that also ask for user input. This is where the issue arises.
Method to be tested:
public abstract class InputHandler {
// Scanner for commands, login message and instructions
public static void start() {
String fullCommand;
String actionCommand;
String commandId;
Scanner scanner = new Scanner(System.in);
// Command loop: asks for valid input and assigns id to variable if necessary
while(true) {
System.out.println("\nEnter command:");
actionCommand = scanner.nextLine().toLowerCase();
//logic to handle different length commands
}
switch (actionCommand) {
case "new lead":
newLead();
break;
case "show leads":
showLeads();
break;
case "quit":
try {
System.out.println("Goodbye!");
Thread.sleep(1000);
System.exit(0);
}catch (InterruptedException e) {
e.printStackTrace();
}
default:
System.out.println("Please enter a valid command");
}
}
}
JUnit Test:
#Test
void startTest() {
System.setIn(new ByteArrayInputStream("new lead\nGustavo Perez\n555555555\nhola#gus.io\nKurts".getBytes()));
InputHandler.start();
assertTrue(!DatabaseManager.getLeads().isEmpty());
}
Again the issue is on the test when the method is called, while it passes "new lead" as standard input (the first string in the byte array) to the Scanner, after the method start() calls the newLead() it no longer continues to pass the values in the byte array.
Thanks for any help!

User input is not calling method (Java)

When I run my program and type user input as (A-F) the program does nothing. I'm trying to figure out why when I enter any of the letters A through Z the program doesn't call the method. If I input one of the numbers they will run perfectly fine and call the methods, but the letters are giving me problems for some reason.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
initializeShipList(); // initial ships
initializeCruiseList(); // initial cruises
initializePassengerList(); // initial passengers
// add loop and code here that accepts and validates user input
// and takes the appropriate action. include appropriate
// user feedback and redisplay the menu as needed
do {
displayMenu();
userInput = scnr.nextLine();
if(userInput.equals("1")) {
addShip();
}
if(userInput.equals("2")) {
editShip();
}
if(userInput.equals("3")) {
addCruise();
}
if(userInput.equals("4")) {
editCruise();
}
if(userInput.equals("5")) {
addPassenger();
}
if(userInput.equals("6")) {
editPassenger();
}
if(userInput.toUpperCase().equals("A")) {
printShipList("active");
}
if(userInput.toUpperCase().equals("B")) {
printShipList("name");
}
if(userInput.toUpperCase().equals("C")) {
printShipList("full");
}
if(userInput.toUpperCase().equals("D")) {
printCruiseList("list");
}
if(userInput.toUpperCase().equals("E")) {
printCruiseList("details");
}
if(userInput.toUpperCase().equals("F")) {
printPassengerList();
}
}while(userInput != "x");
}

String refusing to be stated when it has already been initiated and assigned

I'm trying to take in the user's rock, paper, scissor choice (which is entered as either r, p , or s), but when I try to change and call it, it gives me an error.
Here is my code:
package labs10;
import java.util.Scanner;
import static java.lang.System.*;
public class RPSRunner
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
String full;
String response;
String player = "";
out.print("Select [R,P,S] :: ");
response = kb.next();
if (response.equals("R")) {
full = "Rock";
} else if (response.equals("P")) {
full = "Paper";
} else if (response.equals("S")) {
full = "Scissors";
}
out.println("Player chooses " + full);
RockPaperScissors game = new RockPaperScissors();
game.setPlayers(response);
game.determineWinner();
out.println(game);
}
}
and my error is
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable full may not have been initialized
at labs10.RPSRunner.main(RPSRunner.java:25)
String full;
You declare full with no initial value. If the user types R, P, or S you assign it a value. But what if they type something else? Then full will still be uninitialized. The compiler doesn't like that.
Either assign it a value initially...
String full = null;
...or add a final else clause to handle all other user input.
if (response.equals("R")) {
full = "Rock";
} else if (response.equals("P")) {
full = "Paper";
} else if (response.equals("S")) {
full = "Scissors";
} else {
full = null;
}
Well, if response is neither "R", "P" or "S", full won't be initialized at the point you try to print it with out.println("Player chooses " + full);.
You must assign a default value to it in this case (or throw an exception).

Print statements inside overridden methods not appearing

So I am pretty stuck. I have some code that is being using inside my main method which needs to override the given methods and print out a statement. I got the statement in offer(E s) to work, but can't seem to get the statements in peek() and size() to print. They are functioning properly, but the statements "Peeking at list" and "Reporting list size" just won't print in their methods. If some people can shed some light it would be greatly appreciated! The main is located in a separate file
import java.io.*;
import java.util.*;
import java.awt.*; //for Point
public class StudentList<E>extends LinkedList<E> {
public boolean offer(E s) {
super.offer(s);
System.out.println("Offering "+ s);
return true;
}
public boolean contains(Object o) {
super.contains(o);
return false;
}
public E peek(E slist){
super.peek();
System.out.println("Peeking at list") ;
return slist;
}
public int size(Integer ilist){
System.out.println("Reporting list size");
size(ilist);
//System.out.println("Reporting list size");
return ilist;
}
}
Here is the main method:
public class OfferDriver
{
public static void main ( String[] args)
{
StudentList<Integer> ilist = new StudentList<Integer>( );
StudentList<String> slist = new StudentList<String>( );
String s;
Integer i;
Scanner in = new Scanner(System.in);
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
while (in.hasNext()) {
s = in.next();
if (s.equalsIgnoreCase("stop")) { break; }
slist.offer(s);
System.out.println("Size is: " + slist.size());
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
}
System.out.println("\n" + slist);
String si = slist.peek();
System.out.println("Testing peek(): " + si);
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
while (in.hasNextInt()) {
i = in.nextInt();
ilist.offer(i);
System.out.println("Size is: " + ilist.size());
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
}
System.out.println("\n" + ilist);
int pi = ilist.peek();
System.out.println("Testing peek(): " + pi);
}
}
}
Most likely your peek and size methods are not called. You can always check that with the help of a debugger. You seems to be wrongly overriding the methods. So try adding #override on top of your methods.
LinkedList peek method does not take any param but your method does:
public E peek(E slist)
so it means that you are not overriding the method.
peek() is not the same as peek(E) that you have implemented.
You have defined peek within your StduentList as
public E peek(E slist) {
But are using
String si = slist.peek();
To call it...
In fact, I'm having a hard time trying to figure out why you need to override any of the methods in the first place...
When you are calling the peek() and size() in main, you called this method from
String java.util.LinkedList.peek()
int java.util.LinkedList.size()
this are not your method, which you write in your StudentList Class.

Breaking Out Of A Loop Using A Method In Java

I am trying to use a method to double check before a user exits a while loop in my program.
private static Scanner input = new Scanner(System.in);
public static void ays() {
System.out.println("Are you sure?");
String ays = input.nextLine();
if (ays.equals("Yes")) {
break;
} else {
continue;
}
}
Upon running the program, I get the error break outside switch or loop, and continue outside switch or loop. Is there any way to achieve my goal here?
I guess you are invoking ays() inside a while loop. Let the return type of ays() be boolean and let it return either true or false. Invoke ays() from inside the while loop and based on the value returned by ays(), you continue or break out of the loop.
while (true) {
//Do Something
if (ays()) {
continue();
} else {
break();
}
}

Categories

Resources