I am building an easy Knock Knock game. I have it finished but I would like to add a small feature. It is currently set to accept only a few words/phrases as the correct response and everything else it produces an "error" of sorts. I want to create a class with a list of acceptable works or phrases and have the users input checked against that class.
Here is the test class I created to play with.
import java.util.*;
public class test
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Choose a word");
String userEntry = sc.next().toLowerCase();
if (userEntry.equals(test1.*))
{
System.out.println("We found a match");
}
else if (!userEntry.equals(test1.*))
{
System.out.println("We did not find a match");
}
}
}
The code is of the class that will house the variables.
public class test1
{
public static String a = "yes";
public static String b = "hello";
public static String c = "boo";
}
In the first class, I tried using a wild card to call all of the variables in the class but it produces an error. Any help would be greatly appreciated.
You can't do a wildcard search like that in Java.
You really don't need another class, you can just put all the words/phrases in a List and check against the List.
Example:
import java.util.*;
public class test
{
static Scanner sc = new Scanner(System.in);
// add all the words you need into this array
static String [] wordArr = new String[] { "yes", "hello", "boo" };
// this converts the array to a List
static final List<String> WORDS
= new ArrayList<String>(Arrays.asList(wordArr));
public static void main(String[] args)
{
System.out.println("Choose a word");
String userEntry = sc.next().toLowerCase();
// check if the word is in the list
if (WORDS.contains(userEntry))
{
System.out.println("We found a match");
}
else
{
System.out.println("We did not find a match");
}
}
}
Side Note: You should consider creating the Scanner in the main method and close the scanner when you are done with it.
try this
class test1
{
public static list<String> addElement(){
List<String> list=new ArrayList<>();
list.add("yes");
list.add("boo");
list.add("hello");
}
}
class test{
public static void main(String[] args0)
{
Scanner sc=new Scanner(System.in);
String match=sc.next();
ArrayList<String> list=test1.addElement();
for(String test : list)
{
if(test.equels(match)
print("we have found match");
else
print("no match found"):
}
}
}
Related
I'm taking a coding class using BlueJ, and decided to surprise my teacher with a Text Adventure that uses a Class Runner and another class to have the methods to call. The problem is, I don't know how to use a variable that I established in the Runner, into a method in the Method Class, which I will then call into the Runner. Here is my code:
(This is the runner)
import java.util.*;
public class TextAdventureRunner
{
public static void main (String[]Args)
{
TextAdventureCode run = new TextAdventureCode();
Scanner kb = new Scanner(System.in);
String x = "";
System.out.print("Enter Your Name: : ");
x = kb.nextLine();
System.out.println(x);
run.Hi();
run.HiTwo();
}
}
(This is the code that contains the methods)
import java.util.*;
public class TextAdventureCode extends TextAdventureRunner
{
Scanner kb = new Scanner(System.in);
public static void Hi()
{
System.out.println("Hi" + x);
}
public static void HiTwo()
{
System.out.println("");
}
}
You see, In my method Hi(), there is an error where the x should be. the error reads "cannot find symbol - variable x" even though i extended the class and declared an object in the other class... any help?
You can declare your TextAdventureCode like this:
import java.util.*;
public class TextAdventureCode extends TextAdventureRunner
{
Scanner kb = new Scanner(System.in);
public static void Hi(String x) //Modification
{
System.out.println("Hi" + x);
}
public static void HiTwo()
{
System.out.println("");
}
}
And declare TextAdventureRunner like this:
import java.util.*;
public class TextAdventureRunner
{
public static void main (String[]Args)
{
TextAdventureCode run = new TextAdventureCode();
Scanner kb = new Scanner(System.in);
String x = "";
System.out.print("Enter Your Name: : ");
x = kb.nextLine();
System.out.println(x);
run.Hi(x); // Modification
run.HiTwo();
}
}
i tried to declare a new scanner, it works fine but only at the main.
when i write methods (out of the main of course) it wont recognize the scanner.
import java.util.Scanner;
public class Exe1GenericSort {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
start();
int i = input.nextInt();
}//end main
here it works fine, but at the method "start" it wont let me use "input.next....
tried to write the "Scanner input = new Scanner.... above the main and still wont work...
You need to declare the Scanner as an object outside the main function and then you can use it in other functions.
import java.util.Scanner;
class ScannerTest {
private static Scanner scanner;
public static void main(String[] args){
scanner = new Scanner(System.in);
start();
}
private static void start(){
String input = scanner.nextLine();
System.out.println("Input: " + input);
}
}
NOTE: The scanner object as well as the start function need to be static in order for you to access them inside the main function.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int x= start(input);
System.out.println("enter another number");
int i = input.nextInt();
System.out.println("a number:"+x);
System.out.println("another number"+i);
}
public static int start(Scanner scan)
{
System.out.println("Please enter a number");
int x = scan.nextInt();
return x;
}
to use Scanner in another method
accept a parameter in the method start() and then return x to test the value then print the value in the main method
solved:
import java.util.Scanner;
public class Exe1GenericSort {
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
this one works great !
thank for help ppl.
problem solved ! :)
In class we learned about methods, but I'm having a bit of trouble using them.
In a package called util, I wrote a class called IO.
public class IO {
public static float getFloat(){
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(Scanner s){
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static Scanner getInput (String prompt){
String s = JOptionPane.showInputDialog(prompt);
return new Scanner(s);
}
}
Also in package util, I have my program, called Program 4.
public class Program4 {
public static void main(String[] args) {
IO.getInput("enter 2 integers");
IO.showMessage(Scanner(s));
}
}
What I don't understand is how do I display the 2 integers entered? One is a scanner object and one is string. How do I use the method getInput to show convert the scanner into a string? Am I going to have to write a new method and use parse?
You can get user input without using Scanner. Here is example:
IO Class
public class IO {
public static float getFloat() {
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(String s) {
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static String getInput(String prompt) {
// JOptionPane.showInputDialog() return user input String
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
Program4 Class
public class Program4 {
public static void main(String[] args) {
// IO.getInput() return stored input String
String input = IO.getInput("enter 2 integers");
IO.showMessage(input);
}
}
I want to create a program that can do all the stuff from another code, depending on user input. Something like this:
import java.util.Scanner;
public class Main_Programm1 {
public static void main(String args[]) {
String something = "something";
String something2 = "something2";
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something)) {
//here i want to execute all the code from class Main_Programm2
} else if (action.equals(something2)) {
//here i want to execute all the code from class Main_Programm3 and so on
}
}
}
How do i do it?
Actually, you've got it all done, only creates the Objects that you need ;-)
import java.util.Scanner;
// imports classes;
public class Main_Programm1
{
public static void main(String args[])
{
String something = "something";
String something2 = "something2";
Main_Programm main_prog;
Main_Programm2 main_prog2;
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something))
{
main_prog = new Main_Programm();
//.....
}
else if (action.equals(something2))
{
main_prog2 = new Main_Programm2();
//.....
}
}
}
Suppose i have a class named Invoked, to which i want to call using reflection from Invoker class. but i want to give input from array declared in Invoker class whenever it gets code for input from keyboard.
class Invoked {
public static void main(String ar[]) {
java.util.Scanner s = new java.util.Scanner();
// here i want to give input stored in array except of console from Invoker class.
System.out.println("input given from keyboard is : " + s.next());
}
}
class Invoker {
public static void main(String ar[]) {
// i want to pass array here for keyboard input values like
Class<?> cl = loader.loadClass("Invoked");
Method m = cl.getDeclaredMethod("main", new Class[] {String[].class });
m.setAccessible(true);
m.invoke(null, new Object[] {null });
}
}
java.util.Scanner() reads by default from System.in [stop: there is no default constructor in Scanner, your code won't compile]. You can set it to eg a StringInputStream right before invoking of main (System.setIn()).
class Invoked{
public static void main(String ar[])
{
java.util.Scanner s=new java.util.Scanner(System.in);
//here i want to give input stored in array except of console from Invoker class.
System.out.println("input given from keyboard is : "+s.next());
}
}
class Invoker
{
public static void main(String ar[])
{
//i want to pass array here for keyboard input values like
Class<?> cl = loader.loadClass("Invoked");
Method m=cl.getDeclaredMethod("main", new Class[] { String[].class });
m.setAccessible(true);
System.setIn(new StringBufferInputStream("a b 100"));
m.invoke(null, new Object[] { null });
}
}
Use an ArrayList to make a dynamic array based off how many lines the user inputs.
class Invoked {
public static void main(String[] args) {
java.util.Scanner s = new java.util.Scanner(System.in);
List<String> input = new ArrayList<>;
while(s.hasNext()) {
input.add(s.next());
for(String i : input)
System.out.println("input given from keyboard is : " + i);
}
}
To convert the ArrayList to an array, use
String inArray = input.toArray();
I got the exact code for my problem. Here is the code given below.
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
class Invoked{
public static void main(String ar[])
{
java.util.Scanner s=new java.util.Scanner(System.in);
System.out.println("input given from keyboard is : "+s.next());
int i=s.nextInt()+s.nextInt();
System.out.println("input given from keyboard is : "+i);
}
}
class Invoker
{
public static void main(String ar[])throws Exception
{
Class<?> cl = Class.forName("Invoked");
Method m=cl.getDeclaredMethod("main", new Class[] { String[].class });
m.setAccessible(true);
String inputString="ashish 15 16";
System.setIn(new ByteArrayInputStream(inputString.getBytes()));
m.invoke(null, new Object[] { null });
}
}