Java Project testing methods that require input - java

Java Project
public ArrayShoppingList()
{
// initialise instance variables
super();
}
//public void addItem(int itemPosition,String item){
// super.add(itemPosition,item);
// }
public void addItem(){
System.out.println("Please enter the item you wish to enter into the shopping
List");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
super.add(super.size(),item);
}
public void getPosition(){
System.out.println("Please enter the item name that you wish to find
theposition of");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
super.indexOf(item);
}
public void removeItem(){
System.out.println("Please enter the item number that you wish to remove");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
int itemIndex = super.indexOf(item);
super.remove(itemIndex);
}
I want to know how to test such methods in a Test Class that ask for user input.
The methods call other methods from an ArrayLinearList and pass data that the user has entered in. I want to create code that simulates what the user might enter in.

You can use frameworks like Mockito or Powermock to mock the Scanner. If the class then calls the Scanner for input, you can let your mock return some strings which will be handled as user input by your class. Your class will not see a difference between the "real" scanner and your mock implementation.
See also:
https://code.google.com/p/mockito/
https://code.google.com/p/powermock/

You can use System.setIn(InputSteam)
Here you can specify your own inputstream and add the input you want to it.

Use System.setIn for Unitesting Scanner. For example:
String input = "Your input data";
System.setIn(new ByteArrayInputStream(input.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
Output:
Your input data

Related

Scanner is requiring me to type inputs twice just for one to register

I've been doing a ton of research on this for the past few hours, with no luck. I am pretty sure this is a problem with .next() or .nextLine() (according to my searches). However, nothing has helped me solve my problem.
When I run the code below, I have to type in input twice, and only one of the inputs is subsequently added to the arrayList (which can be seen when you print the contents of the arrayList).
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
if(console.next().equals("done")) break;
//console.nextLine(); /*according to my observations, with every use of .next() or .nextLine(), I am required to type in the same input one more time
//* however, all my google/stackoverflow/ reddit searches said to include
//* a .nextLine() */
//String inputs = console.next(); //.next makes me type input twice, .nextLine only makes me do it once, but doesn't add anything to arrayList
strings.add(console.next());
}
System.out.println(strings); //for testing purposes
console.close();
}
}
Problem with your code is that you are doing console.next() two times.
1st Inside if condition and
2nd while adding to ArrayList.
Correct Code :
public class TestClass{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
String input = console.next();
if(input.equals("done")) break;
strings.add(input);
System.out.println(strings);
}
System.out.println(strings); //for testing purposes
console.close();
}
}
In your code, you are asking for two words to be inserted. Just remove one of them.
Use it this way:
String choice = console.next();
if (choince.equals('done')) break;
strings.add(choice);

how to create multiple scanner elements in java [duplicate]

This question already has an answer here:
How to use multiple Scanner objects on System.in?
(1 answer)
Closed 26 days ago.
I have a main function in which I use scanner to read an integer from console.
Inside this main function, we can access another function which also uses scanner to read an integer. So, the program swings between these two functions many times. But, Java.util.scanner throws an exception. Is there any way to overcome this?
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
int buy;
Scanner sc = new Scanner(System.in);
buy = sc.nextInt();
user = dummy2();
sc.close();
}
static boolean dummy2(){
Scanner sc1 = new Scanner(System.in);
sc1.close();
}
}
First of all, it would make the question much easier to answer if you gave more information, such as the exception and its message, and maybe source code.
If the exception is a NoSuchElementException, the direct problem is that the function is closing the Scanner. When the scanner is closed, it also closes the underlying ImputStream. This makes all other Scanner on that input invalid.
If the exception is InputMismatchException, then the input is not an int.
If the exception is IllegalStateException, then the scanner has been closed, this could happen is the function and the main method are using the scanner, and one closes it.
However, you should not be taking user input in functions. This limits future use, say if you wanted to later add a GUI or make the same calculation based off a number not gotten from the user, then you would need rewrite the function. The function should take a int as a parameter, which the main method should get from the user. Only the main method and other methods directly relating to user input, such as the Scanner's methods, should read user input.
Use the same Scanner object.
import java.util.Scanner;
public class dummy {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int buy;
buy = sc.nextInt();
user = dummy2();
//Do more stuff with the same scanner
//close it when done
}
static boolean dummy2(){
//Scan stuff
int nbr = sc.nextInt();
}
I would suggest something like that:
import java.util.Scanner;
public class dummy {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int buy;
buy = sc.nextInt();
user = dummy2();
sc.close();
}
static boolean dummy2(){
//lets scan a string.
sc.nextLine();
}
}
Reusable objects! Isn't that nice?

java : get object name from scanner input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am teaching myself Java from books and videos from internet.
i know the bellow code is wrong but how can I make object name read from a variable like this?
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
String ObjectName=input.next();
className ObjectName=new className ();
ᴋᴇʏsᴇʀ , Pshemo ,Brian Vanover i edit my question
i have class named BankAccount and another main class with this code
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
System.out.println("Please Enter ID");
int id=input.nextInt();
System.out.println("Please Enter Name");
String name = input.next();
System.out.println("Please Enter Balance");
double balance = input.nextDouble();
String client=input.next();
BankAccount client = new BankAccount (id,name,balance);// i know this code line is worng
client.printStatement();
If you are asking how to create instance of class based only on class name then you can try with
Scanner input =new Scanner (System.in);
String className = input.nextLine();
Class<?> clazz = Class.forName(className);
Object o = clazz.newInstance();
Now if you pass full.package.name.of.YourClass and if this class has accessible no-argument constructor you should be able to create its instance via newInstance method.
Edit.
It seems that you want to store your object on some name provided by user. You can't do that explicitly as variable name, but you can make some map from String to yourObject using Map interface. Your code can look like
Scanner input = new Scanner(System.in);
System.out.println("Please Enter ID");
int id = input.nextInt();
System.out.println("Please Enter Name");
String name = input.next();
System.out.println("Please Enter Balance");
double balance = input.nextDouble();
String client = input.next();
BankAccount clientAccount = new BankAccount(id, name, balance);
client.printStatement();
Map<String,BankAccount> map = new HashMap<>();
map.put(client, clientAccount);
later you can just get account of client by using map.get and get account details like
map.get(client).getID();//assuming that you have getter for ID
This can be handled by using an enum or if-logic If-logic will be ok if you expect a limited number of possible inputs:
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
String objectName = input.next();
if (ObjectName.equals("obj1")) {
Obj1 myObject = new Obj1();
} else {
Obj2 myObject = new Obj2();
}
First file name Out.java & second file name in.java
//first file's code start here
public class Out {
public static void main(String[] args) {
in inObject =new in();
inObject.ikl();
}
}
//second file's code start here
import java.util.Scanner;
public class in {
public static int ikl() {
Scanner input=new Scanner(System.in);
int j=input.nextInt();
System.out.println(j);
return j;
}
}

Entering commands into a arraylist

So I have this assignment, and it says to create a arraylist using standard input, and constantly prompt the user for commands. Now, I understand how to add commands, WITHIN the code, but I dont understand how to take what the user puts in, and turn that into a command in the arraylist. Here's what I got so far:
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner s = new Scanner(System.in);
Scanner n = new Scanner(System.in);
System.out.println("Enter a command:");
String command = s.nextLine();
System.out.println("If you entered 'add', then enter a name:");
String input = n.nextLine();
}
}
EDIT New Code:
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner e = new Scanner(System.in);
System.out.println("Enter command, or type 'quit' to exit");
String quit = e.next();
boolean exit = quit;
if(exit = true){
System.exit();
}
}
}
You can request that the user types in his commands and then check using the method from the String class equalsIgnoreCase() and compare it and see if it is the same as add, remove, etc. (whatever commands you need). Use if-else statements to implement the logic. For example if user input resolves to add, then you add an element. If user input is not any of the common functions, then print message that there was an error and so on. I cannot type out the answer in code as this is an assignment.
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner e = new Scanner(System.in);
System.out.println("Enter command, or type 'quit' to exit \n");
while (!e.nextLine().equalsIgnoreCase("quit")) { // As long as input not equal to quit
if (e.nextLine().equalsIgnoreCase("add") {
System.out.println("Enter name to add:\n");
String name = e.nextLine();
names.add(name);
}
if (e.nextLine().equalsIgnoreCase("remove") {
System.out.println("Enter name to remove:\n");
String name = e.nextLine();
names.remove(name);
}
}
if(e.nextLine().equalsIgnoreCase("quit"){
scanner.close();
System.exit();
}
}
}
Check out the add() method in the java.util.List interface. Might help.

Select a function depending upon the input in java

If I have the two functions below.
How can I select the function that will be chosen?
I imagine there is either some form of statement to determine the content of the scanner and therefore only have one function. Or it would be something that is passed to the function.
public static int questionAsk(String question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question+"\n");
System.out.print ("Answer: ");
return scan.nextInt();
}
public static String questionAsk(String question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question+"\n");
System.out.print ("Answer: ");
return scan.nextLine();
}
There is no way for the compiler to know which one of those methods you are calling. You could make it type safe by changing the String Types to something else, like this:
public static int questionAsk(IntQuestion question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question.toString() +"\n");
System.out.print ("Answer: ");
return scan.nextInt();
}
public static String questionAsk(StringQuestion question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question.toString() +"\n");
System.out.print ("Answer: ");
return scan.nextLine();
}
And adding two new classes:
public class IntQuestion extends String{
public IntQuestion(String question){
super(question);
}
}
public class StringQuestion extends String{
public StringQuestion(String question){
super(question);
}
}
When you construct an IntQuestion of StringQuestion, you can simply construct them the same way you would construct a String if you called the constructor:
IntQuestion intQuestion = new IntQuestion("Some String Here");
This is just a little bit of syntactic sugar to get the compiler to play nice and select the correct method based on the type.
I hope this helps.
You should first scan, parse and then call the required function using if else or switch case.
What you are doing right now is using the same code in two functions, and not reusing the code. Just use a single scan instead

Categories

Resources