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
Related
I am very new in programming into Java.
My question is that I have a code (see below) and I want to compare them with if statement. An errors occur at line 9 (string test) and 11(if(test.equals). I completely do not have idea.
I have made a code with int and it works perfect, but that.
package bucky;
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
if (test.equals("YES")) {
System.out.println("YES");
} else {
System.out.println("TIS IS ELSE");
}
}
}
You are almost there... define YES as string and that it
String test = sc.nextLine();
String YES = "yes";
if (test.equals(YES)) {
or even better use equalsIgnoreCase() so you can get rid off the case sensitive input
if (test.equalsIgnorecase(YES))
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);
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 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
I am trying to write this code for a class, but I don't want to use an array (String word[]). How do I change it so I use a regular method with parentheses?
Also, one of my friends helped and I am trying to learn, and I forgot what the alright(s); thing does. I tied to figure it out, but have failed. I think it creates and object for the scan, but I don't really know.
import java.util.Scanner;
public class WordLines{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
alright(s);
}
public static void alright(String s){
String word[]=s.split(" ");
for(int j=0;j<word.length; j++){
System.out.println(word[j]);
}
}
}
Thank you so much for the help!!! :)
One way to achieve similar results without the array is to use an additional instance of the Scanner class to parse the string:
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
Scanner parse = new Scanner(s);
while (parse.hasNext()) {
System.out.println(parse.next());
}
Link: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html