import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//star my method lab
public class Method extends JPanel {
//two array lists that I am going to use.
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public void loadEnglishWords() {
//input my file
String filename = "english.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
//scan all array line by line
while (s.hasNextLine()) {
String line = s.nextLine();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public void loadFrenchWords() {
String filename = "french.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public String lookup(String word){
for (int i = 0; i < english.size();i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r == ("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null,a,"RESULT!",JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
#Override
public void init() {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
//My problem is that everytime I compile this program the error message would be:
"Method.java:88: error: method does not override or implement a method from a supertype
#Override
^
1 error"
//This program is to translate french words to english words using arraylist
I`m using a .txt file for my set of english and french words and have it run through arraylist to translate
//In my program I need to use a JPanel or pop-up box to ask the user to input the word that they wish to translate
//Please note that I am a beginner with Java, please somebody help me and point out on where I got it wrong so I can change it. Thank you so much!
What the error is saying is that in line 88, you are using the #Override to redefine a method named init from parent class JPanel. But because JPanel is what it is (i.e. a part of Java), it does not have init method, you can not redefine it, hence the error. Most likely, you should just remove the #Override, which will mean you want to add a new method instead of redefining it.
Inheritance is a mechanism where you take an existing class and modify it according to your needs. In your case, your class is named Method and it extends (inherits from) JPanel, so JPanel is the supertype of your class.
If you're just beginning, go read and educate yourself on object-oriented concepts. There are many tutorials, including YouTube videos. Happy learning!
Aside from what was previously mentioned, you need to change a few things:
public void init() { should be public static void main(String args[]) {
Then you need to make your methods static, i.e.
public static void loadEnglishWords() {
Also, the arrayLists need to also be static
And one other thing, you should compare with .equals() and not ==
I've re-written your code slightly and now it should work:
static ArrayList<String> english = new ArrayList<>();
static ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public static void loadEnglishWords() {
//input my file
try {
Scanner s = new Scanner(new File("english.txt"));
//scan all array line by line
while (s.hasNextLine()) {
String line = s.next();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public static void loadFrenchWords() {
try {
Scanner s = new Scanner(new File("french.txt"));
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public static String lookup(String word) {
for (int i = 0; i < english.size(); i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public static void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r.equals("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null, a, "RESULT!", JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
public static void main(String args[]) {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
Related
I'm trying to learn about exception handling. I can't seem to get
String[] a = names(scnr); To throw an out of bounds exception when it goes beyond 3 elements. I know, most people hate the out of bounds error and I'm trying to make it happen and for the life of me I cannot figure out what I'm doing wrong. Been at it all day and googled all kinds of stuff. But I cannot seem to find exactly what I'm looking for. So I could use some help and perspective.
So I'm inputting a full string that I'm delimiting (trim and splitting) based on commas and spaces and then the pieces are being stored into an array (String []name), then passed to main to be output with String[] a. So it's not erroring when I go beyond 3 elements no matter how I do it. I can just not display anything beyond a[4]. But that's not really what I'm trying to do. Its my first java class so be gentle haha.
Any suggestions?
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
If I understand you correctly, you want to throw an ArrayOutOfBoundsException if the names array does not contain exactly 3 elements. The following code is the same as the one you wrote with an if-statement to do just that.
import java.util.*;
public class ReturnArrayExample1
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
for (int i = 0; i < 3; i++)
{
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr)
{
String[] name = new String[3]; // initializing
boolean run = true;
do
{
try
{
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if(rawData.isEmpty())
{
System.err.println("Nothing was entered!");
throw new Exception();
}
else
{
name = rawData.trim().split("[\\s,]+");
if (name.length != 3) {
throw new ArrayIndexOutOfBoundsException();
}
run = false;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Input is out of bounds!\nUnsuccessful!");
}
catch(Exception e)
{
System.err.println("Invalid entry!\nUnsuccessful!");
}
}
while(run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
If you want java to throw an ArrayIndexOutOfBoundException you have to preserve the created names instance and let java copy the array into your names array:
String[] names=new String[3];
String[] rawElements=rawData.trim().split("[\\s,]+");
System.arraycopy(rawElements, 0, names, 0, rawElements.length);
output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at stackoverflow.OutOfBound.main(OutOfBound.java:8)
As far as I understand, you are expecting an exception (ArrayIndexOutOfBoundsException) to the thrown at line
name = rawData.trim().split("[\\s,]+");
with an argument that the size of array (name) is fixed to 3, and when if the input is beyond 3 then the exception must be thrown; which is not the case.
The reason is in the way assignment happens in java. When you declare String[] name = new String[3];, then an object is created in java heap and its reference is assigned to variable name which is in stack memory.
And when this line name = rawData.trim().split("[\\s,]+"); gets executed then a new array object is created in heap and the variable name starts pointing to the newly created array object on heap. Note: the old object will get available for garbage collection after some time.
This eventually changes the length of the array variable (name) and you do not get any ArrayIndexOutOfBoundsException.
You can understand this more clearly by printing the object on console, like System.out.println(name); after its initialisation and post its assignment.
I will also suggest you to refer this link (https://books.trinket.io/thinkjava2/chapter7.html#elements) to understand how array are created, initialised and copied etc..
Code with system.out commands (for understanding)
import java.util.Scanner;
public class ReturnArrayExample1 {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
String[] a = names(scnr);
System.out.println("Variable (a) is referring to > " + a);
for (int i = 0; i < 3; i++) {
System.out.println(a[i] + " in index[" + i + "].");
}
scnr.close();
}
public static String[] names(Scanner scnr) {
String[] name = new String[3]; // initializing
System.out.println("Variable (name) is referring to > " + name);
boolean run = true;
do {
try {
System.out.println("Enter 3 names separated by commas ',':(Example: keith, mark, mike)");
String rawData = scnr.nextLine();
if (rawData.isEmpty()) {
System.err.println("Nothing was entered!");
throw new Exception();
} else {
name = rawData.trim().split("[\\s,]+");
System.out.println("Now Variable (name) is referring to > " + name);
run = false;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Input is out of bounds!\nUnsuccessful!");
} catch (Exception e) {
System.err.println("Invalid entry!\nUnsuccessful!");
}
} while (run == true);
System.out.println("Successful!");
scnr.close();
return name;
}
}
I you want to throw exception when input is more than 3 then there are many ways to do it. One suggestion from #mohamedmoselhy.com is also decent.
I'm nearly finished with a program that gathers the user's inputs (keywords) and displays them. I have it functioning in that regard but I also need to prevent duplicate keywords from being added to the List using a conditional if statement. I know I'm on the right track, but having trouble wrapping my mind around the syntax and use of a boolean to compare the entered keyword with the existing ArrayList.
I know there are methods such as Hash/Set but I'd like to be able to do it with the conditional statement before I move onto other techniques. Every answer I've found in the search seems to explain the use of Hash.
Thanks!
UPDATE: Iv'e edited my code to what I currently have based on #Jacob 's answer and this is what I was looking for, so thanks for the response. But it's still not removing duplicates, it's like it's not checking the array and skipping right to alreadyExists == false conditional statement. Or am I not comparing the values correctly?
import java.util.*;
public class KeywordData {
private ArrayList<Keyword> keywords = new ArrayList<Keyword>();
public void create() {
InputHelper inputHelper = new InputHelper();
String prompt = "";
boolean isTrue = true;
while (isTrue) {
prompt = inputHelper.getUserInput("Enter a string, otherwise type 'n' to exit:");
if (!prompt.equals("n")) {
Keyword keyword = new Keyword();
keyword.setUserKeyword(prompt);
boolean alreadyExists = false;
for (Keyword keyword1 : keywords) {
if (keyword1.equals(keyword)) {
alreadyExists = true;
}
}
if (alreadyExists == false) {
keywords.add(keyword);
} else {
System.out.println("You already added that word");
}
} else {
break;
}
}
}
public void displayKeywords() {
System.out.println();
System.out.println("********** Your unique user keywords **********");
for (Keyword keyword : keywords) {
keyword.display();
}
System.out.println();
}
}
This is how I did it, I showed my whole program because I changed some of your custom classes to just strings, and didn't really know what those custom classes did.
import java.util.*;
import java.io.Console;
public class KeywordData {
private ArrayList<String> keywords = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
public void create() {
String prompt = "";
boolean isTrue = true;
while (isTrue) {
System.out.println("Enter a string, otherwise type 'n' to exit:");
prompt = reader.next();
if (!prompt.equals("n")) {
boolean alreadyExists = false;
for (String keyword1 : keywords) {
if (keyword1.equals(prompt)) {
alreadyExists = true;
}
}
if (alreadyExists == false) {
keywords.add(prompt);
}else {
System.out.println("You already added that word");
}
} else {
break;
}
}
}
public void displayKeywords() {
System.out.println();
System.out.println("********** Your unique user keywords **********");
for (String keyword : keywords) {
System.out.println(keyword);
}
}
public static void main(String[] args) {
KeywordData kd = new KeywordData();
kd.create();
kd.displayKeywords();
}
}
But the easier way to check is like this
if (!prompt.equals("n")) {
if (keywords.contains(prompt)) {
System.out.println("You already added that word");
}else {
keywords.add(prompt);
}
} else {
break;
}
I would like to start off by saying that if this is common knowledge, please forgive me and have patience. I am somewhat new to Java.
I am trying to write a program that will store many values of variables in a sort of buffer. I was wondering if there was a way to have the program "create" its own variables, and assign them to values.
Here is an Example of what I am trying to avoid:
package test;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int inputCacheNumber = 0;
//Text File:
String userInputCache1 = null;
String userInputCache2 = null;
String userInputCache3 = null;
String userInputCache4 = null;
//Program
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("User Input: ");
String userInput;
userInput = scan.nextLine();
// This would be in the text file
if (inputCacheNumber == 0) {
userInputCache1 = userInput;
inputCacheNumber++;
System.out.println(userInputCache1);
} else if (inputCacheNumber == 1) {
userInputCache2 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 2) {
userInputCache3 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 3) {
userInputCache4 = userInput;
inputCacheNumber++;
}
// And so on
}
}
}
So just to try to summarize, I would like to know if there is a way for a program to set an unlimited number of user input values to String values. I am wondering if there is a way I can avoid predefining all the variables it may need.
Thanks for reading, and your patience and help!
~Rane
You can use Array List data structure.
The ArrayList class extends AbstractList and implements the List
interface. ArrayList supports dynamic arrays that can grow as needed.
For example:
List<String> userInputCache = new ArrayList<>();
and when you want to add each input into your array like
if (inputCacheNumber == 0) {
userInputCache.add(userInput); // <----- here
inputCacheNumber++;
}
If you want to traverse your array list you can do as follows:
for (int i = 0; i < userInputCache.size(); i++) {
System.out.println(" your user input is " + userInputCache.get(i));
}
or you can use enhanced for loop
for(String st : userInputCache) {
System.out.println("Your user input is " + st);
}
Note: it is better to put your Scanner in your try catch block with resource so you will not be worried if it is close or not at the end.
For example:
try(Scanner input = new Scanner(System.in)) {
/*
**whatever code you have you put here**
Good point for MadProgrammer:
Just beware of it, that's all. A lot of people have multiple stages in their
programs which may require them to create a new Scanner AFTER the try-block
*/
} catch(Exception e) {
}
For more info on ArrayList
http://www.tutorialspoint.com/java/java_arraylist_class.htm
We have an assignment for an intro to java class im taking that requires us to program a parrot.
Essentially we have an output
" What do you want to say?
The User types in his input
" Blah Blah Blah"
And then the parrot is supposed to repeat
"Blah Blah Blah"
I have achieved this.
package parrot;
import java.util.Scanner;
public class Parrot {
public static void main(String[] args) {
System.out.print(" What do you want to say? ");
Scanner input = new Scanner(System.in);
String Parrot = input.nextLine();
System.out.println("Paulie Says: " + Parrot);
}
}
This gives me the exact results I need, but then I read in the lab instructions it wants us to do it in 2 files?
Add 2 files to the project: Parrot.java and ParrotTest.java
In Parrot.java do the following:
Create a public class called Parrot
Inside the class create a public method called speak. The method speak has one String parameter named word and no return value (i.e. return type void) The method header looks like this: public void speak(String word)
The parrot repeats anything he is told. We implement this behavior by printing the word passed as an argument
And what I think im being asked to do is call it from another file? Can someone explain to me how to do this as im not exactly sure whats going on?
Yes your program performs the given task, but not in the manner you are asked. Your main method should be executed from inside the ParrotTest.java file. In this file (ParrotTest.java), you will need to create an instance of a class (you can call it Parrot) by calling a constructor.
Inside your Parrot.java you will create a method called 'speak' which accepts String word.
Going back to the main method: Here you will ask for user input, capture the input in a String 'word' and pass it as an argument to the speak method you created. Once your method has this argument, you can print it's content out to the console.
Parrot would have the following
public class Parrot
{
public void speak( String word )
{
System.out.printf("%s", word);
}
}
Parrot Test would have the following
import java.util.Scanner;
public class ParrotTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What would you like to say to the parrot?: ");
String words = input.nextLine();
Parrot myParrot = new Parrot();
myParrot.speak(words);
}
}
I don't know if you have to use scanner but this is how i would do it.BTW this code works with Jcreator.
public static void main(String[] args) {
String say = IO.getString("Say something") // This is asking the user to say something
System.out.print(name);
}
If you want it to loop 10 times then
then do this
public static void main(String[] args) {
String say = IO.getString("Say something"); // This is asking the user to say something
int count = 10; // it will loop 10 times
while (count >= 10) {
System.out.print(name);
say = IO.getString("Say something");
count++;
}
By the way if you don't have IO class you can you this. Just copy this code into jcreator and say it where you save all your codes.
/**
* #(#)IO.java
* This file is designed to allow HCRHS students to collect information from the
* user during Computer Science 1 and Computer Science 2.
* #author Mr. Twisler, Mr. Gaylord
* #version 2.01 2014/12/21
* *Updated fix to let \t work for all input/output
* *Added input methods to allow for console input
* *Allowed all get methods to work with all objects
* *Updated format methods to use String.format()
*/
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class IO {
// Shows a message in a popup window
public static void showMsg(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
JOptionPane.showMessageDialog(null, text, "HCRHS",
JOptionPane.PLAIN_MESSAGE);
}
/*********************************User Input Methods***************************
* All user input methods get the data type mentioned in their name and return
* a default value if the user enters an incorrect responce.
******************************************************************************/
// Returns String typed by user, default value is ""
public static String getString(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
String ans = JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE);
if(ans == null) {
return "";
}
return ans;
}
public static String nextString() {
Scanner scan = new Scanner(System.in);
String ans = scan.nextLine();
scan.close();
if(ans == null) {
return "";
}
return ans;
}
// Returns int typed by the user, default value is 0
public static int getInt(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Integer.parseInt(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
return 0;
}
}
public static int nextInt() {
Scanner scan = new Scanner(System.in);
int ans;
try {
ans = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
ans = 0;
}
scan.close();
return ans;
}
// Returns double typed by the user, default value is 0.0
public static double getDouble(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Double.parseDouble(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
return 0;
}
}
public static double nextDouble() {
Scanner scan = new Scanner(System.in);
double ans;
try {
ans = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
ans = 0;
}
scan.close();
return ans;
}
// Returns char typed by the user, default value is ' '
public static char getChar(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE).charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
return ' ';
}
}
public static char nextChar() {
Scanner scan = new Scanner(System.in);
char ans;
try {
ans = scan.nextLine().charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
ans = ' ';
}
scan.close();
return ans;
}
// Returns boolean typed by the user, default value is false
public static boolean getBoolean(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
int n = JOptionPane.showOptionDialog(null, text, "HCRHS",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, new Object[]{"True", "False"}, 1);
return (n == 0);
}
public static boolean nextBoolean() {
Scanner scan = new Scanner(System.in);
String bool = scan.nextLine().toLowerCase();
scan.close();
if (bool.equals("true") || bool.equals("t") || bool.equals("1")) {
return true;
} else {
return false;
}
}
/******************************Formatting Methods******************************
* Format is overloaded to accept Strings/int/double/char/boolean
******************************************************************************/
public static String format(char just, int maxWidth, String s) {
if (just == 'l' || just == 'L') {
return String.format("%-" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'r' || just == 'R') {
return String.format("%" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'c' || just == 'C') {
return format('l', maxWidth, format('r',
(((maxWidth - s.length()) / 2) + s.length()), s));
} else {
return s;
}
}
public static String format(char just, int maxWidth, int i) {
return format(just, maxWidth, String.format("%d", i));
}
public static String format(char just, int maxWidth, double d, int dec) {
return format(just, maxWidth, String.format("%,." + dec + "f", d));
}
public static String format(char just, int maxWidth, char c) {
return format(just, maxWidth, String.format("%c", c));
}
public static String format(char just, int maxWidth, boolean b) {
return format(just, maxWidth, String.format("%b", b));
}
/*********************************Fancy Expirmental Methods********************/
public static String choice(String... options) {
String s = (String)JOptionPane.showInputDialog(null,
"Pick one of the following", "HCRHS",
JOptionPane.PLAIN_MESSAGE, null, options, null);
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
return s;
}
return "";
}
public static String readFile(String fileName) {
String ans ="";
try {
Scanner scanner = new Scanner(new File(fileName));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
ans += scanner.next()+"\n";
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return ans;
}
public static void writeFile(String fileName, String data) {
try {
FileWriter fw = new FileWriter(fileName, true);
fw.write(data);
fw.close();
} catch(java.io.IOException e) {
e.printStackTrace();
}
}
}
This is my first post, and I'm only new to Java, so sorry if it is not up to scratch.
I have been writing a text-based adventure game in Java, and my code has failed me in one place - the parser. There is no error, it just doesnt work. It takes in the input but does nothing about it. It is very simple, and looks something like this:
public static void getInput(){
System.out.print(">>"); //print cue for input
String i = scan.nextLine(); //get (i)nput
String[] w = i.split(" "); //split input into (w)ords
List words = Arrays.asList(w); //change to list format
test(words);
}
The test method just searches the list for certain words using if(words.contains("<word>")).
What is wrong with the code and how can I improve it?
How about keeping the array and using something like this:
String[] word_list = {"This","is","an","Array"}; //An Array in your fault its 'w'
for (int i = 0;i < word_list.length;i++) { //Running trough all Elements
System.out.println(word_list[i]);
if (word_list[i].equalsIgnoreCase("This")) {
System.out.println("This found!");
}
if (word_list[i].equalsIgnoreCase("is")) {
System.out.println("is found!");
}
if (word_list[i].equalsIgnoreCase("an")) {
System.out.println("an found!");
}
if (word_list[i].equalsIgnoreCase("Array")) {
System.out.println("Array found!");
}
if (word_list[i].equalsIgnoreCase("NotExistant")) { //Wont be found
System.out.println("NotExistant found!");
}
}
You will get the following output:
This found!
is found!
an found!
Array found!
As you can see you needn't convert it to a List at all!
Here is how I would do this:
public class ReadInput {
private static void processInput (List <String> words)
{
if (words.contains ("foo"))
System.out.println ("Foo!");
else if (words.contains ("bar"))
System.out.println ("Bar!");
}
public static void readInput () throws Exception
{
BufferedReader reader =
new BufferedReader (
new InputStreamReader (System.in));
String line;
while ((line = reader.readLine ()) != null)
{
String [] words = line.split (" ");
processInput (Arrays.asList (words));
}
}
public static void main (String [] args) throws Exception
{
readInput ();
}
}
Sample session:
[in] hello world
[in] foo bar
[out] Foo!
[in] foobar bar foobar
[out] Bar!