I am having an issue with a java program that I have to make for class. I am to take two letters and convert those to a location. I am to then take a message and encrypt it using a basic character swap. I seem to be having an issue with the fact that a call in my Driver file can't see the method I am trying to call in my Actions file. I sure I am missing something simple and doing it wrong but the more I read the documentation the more confused I become. Could someone please explain to me what I am doing wrong. I am trying to call my getCountry method which is in my Actions file from my Driver file. The error is at the line
locH = loc.getCountry(locationLetters);
Driver.java
/**
Program Name: Action
Date:4/14/2016
Program Description: This program is going to handle the window where the user enters data.
It is also going to be what is going to call the methods of the Actions class
Methods: Driver(),
*/
import javax.swing.*; // For the Swing classes
import java.awt.event.*; // For the ActionListener Interface
import java.util.Scanner; //for the keyboard
public class Driver extends JFrame
{
//delcare
private String locationLetters; //this is going hold the users letter selection
private String message; //this is going to hold the users message
private String locH; //for the holder of location selection
private String messH; //to hold the message before change it to an array
Scanner keyboard = new Scanner (System.in);//to make the keyboard
/**
This method is the constuctor that is going to make the window for the program to use.
*/
public Driver()
{
System.out.println("sup nerd");
yourmom();
}//end of Driver()
public String yourmom()
{
System.out.println("Please entner the two charater key for the location you want to message");
locationLetters = keyboard.next();
System.out.println("Please enter the message you would like to have encrypted.");
message = keyboard.next();
locH = loc.getCountry(locationLetters);
return locH;
}//end of yourmom()
public static void main(String[] arg)
{
Actions loc = new Actions();
Actions mess = new Actions();
new Driver();
}//end of main
}//end of Driver class
Actions.java
/**
Program Name: Action
Date:4/14/2016
Program Description: This program is going to handle all the encryption actions as well
loction where the message is being sent.
Methods:Location(),
*/
public class Actions
{
//decare
public String messE; //this is for the message that is going to be ecrypted
public String getCountry(String locHA)
{
locHA.toUpperCase();
if(locHA == "FR")
locHA = "France";
if(locHA == "GB")
locHA = "Great Britain";
if(locHA == "CA")
locHA = "Canada";
if(locHA == "JA")
locHA = "Japan";
if(locHA == "RU")
locHA = "Russia";
if(locHA == "GE")
locHA = "Germany";
if(locHA == "AU")
locHA = "Australia";
if(locHA == "MX")
locHA = "Mexico";
return locHA;
}
}//end of action class
I know that this could be done in one file but my teacher wants it in two. I know I am missing something simple but I do not understand the documentation that I have been reading in regards to using objects. Could you please point out what I have done wrong? I would be quite grateful. Thank you.
Change your main so that you pass the important data into Driver:
public static void main(String[] arg) {
Actions loc = new Actions();
Actions mess = new Actions();
new Driver(loc, mess);
}
Then use those Actions inside of the main constructor:
public Driver(Actions loc, Actions mess) {
// use parameters to set fields so that the parameter references can be
// used elsewhere in the class
this.loc = loc;
this.mess = mess;
System.out.println("sup nerd");
yourmom(loc); // and pass references where needed
}
And similarly then use the loc reference inside of the yourmom() method
Also, don't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if(locHA == "FR")
locHA = "France";
do
// always use curly braces too!
if("FR".equals(locHA)) {
locHA = "France";
}
or
// if you want to allow more liberal capitalization
if("FR".equalsIgnoreCase(locHA)) {
locHA = "France";
}
Put
Actions.getCountry();
in your main class.
And you can take the public out of the second class as it is not as easily accessible.
Related
I am trying to make this program That uses the scanner method. A user would type their name, then the ScannerToolclass would store that information into the guess string varible. An Object is created in the portation class as ScannerTool cool = new ScannerTool(); for both the justPoints() and post() methods. The portation class takes the objects and store what the user types into a String variable called hope as String hope = cool.scannerT() it then takes what the user types and executes an if statement. I create an object for the portation class and ScannerTool inside the MainTest and then I run it from MainTest class.
My problem is that when I run this program it throws an exception error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.justPoints(portation.java:12)
at MainTest.main(MainTest.java:20)
However, when i dont use the portation class and just go from ScannerTool to MainTest with the same code from portation it works. The weird part is that when I do it the original way there are no errors presented at the lines, only when I execute the whole program
What I tried: I tried to change the return types in the methods in portation from int and string to void, that didn't work. I tried looking at the lines that said where the error occured, but that didn't help becuase everything looked correct. Since it's not throwing actual errors on the IDE before running i'm at a loss.
the code:
The code that works:
MainTest
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
//portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
int points = 0; // taken from the portation class
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println("the name " + hope + " is cool");
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
} //taken from the portation class
System.out.println(points);
//damn.post();
//damn.justPoints();
}
}
portation: not in use
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
the code that doesn't work
MaintTest:
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
damn.post();
damn.justPoints();
}
}
portation:
public class portation {
public void justPoints() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
int points = 0; //setup the points variable
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println(points);
}
public void post() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
System.out.println("the name " + hope + " is cool"); //printed what the user typed
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
}
}
}
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
when I use the way that doesn't work this is what runs:
What your name my guy? chris
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.post(portation.java:21)
at MainTest.main(MainTest.java:9)
What would be the answer I'm looking for? I would like to know, why am I getting this error and what do I need to do to fix it?
The problem comes from the fact that System.in is a specific InputStream - it is static and only created once. In your case, you read from it once and immediately close it (when you close the Scanner). When you try to read from a closed stream, it will throw an exception, NoSuchElementException in this case. When working with files it usually isn't a problem because you could always create a new InputStream.
What you need to do here is to make sure you will close the InputStream only when you're done with reading everything. You could make the Scanner variable static, create a new method for closing it and call it only when you're done with reading.
I'm having an issue that has been giving me a an error saying java.lang.StackOverflowError: null. My program is sort of like a lottery, a random number is chosen, and based off the number, your item is chosen from a array. Now this works all handy and dandy, but when i try to insert the item received into an inventory. I get that error. Im pretty sure i set up my class wrong but i don't know how to construct an array in a separate class that receives data from another class, and returns the data back to the same class. Enough chit chatting, heres what my code looks like so far. (please dont mind the extra variables as this is a cropped portion of my code)
public class inventory {
private int inventorymain;
public String[] inventorymain() {
String[] inventorymain;
return inventorymain();
}
}
import java.util.Scanner;
import java.util.Random;
public class glue {
public static void main(String [] args) {
inventory inv = new inventory();
allskins a = new allskins();
Scanner s = new Scanner(System.in);
int selection = 0;
int invcount = -1;
Random rand = new Random();
do {
System.out.println(d.menue());
selection = s.nextInt();
if (selection == 1) {
invcount++;
int random = rand.nextInt(208);
System.out.println("You opend a: ");
System.out.println(a.allskins()[random]);
System.out.println("Your item has been put in your inventory, select inventroy from the menue to view all items.");
System.out.println("");
inv.inventorymain()[invcount] = (a.allskins()[random]);
}
}while (selection != 6);
}
}
Thank you
You're entering infinite recursive loop calling inventorymain()
public class inventory {
private int inventorymain;
public String[] inventorymain() {
String[] inventorymain;
return inventorymain(); // recursive call here without escape condition
}
}
It's better to keep the method name and variable name different to avoid such cases.
I'm currently working on somekind text-based 'RPG' game. I made two classes, first one is supposed to simulate road from one town to another and doing so there is a possibility that player will encounter enemy. Fighting logic is placed in another class and when player dies I call method which is supposed to load game from previous save or create new character and that works perfectly fine, but even when player died road is continued instead of breaking loop. LeaveTown class looks like this:
public class WorldMap {
boolean running=true;
public void leaveTown(Character character){
EnemyFactory factory = new EnemyFactory();
PerformAtack atack = new PerformAtack();
StringBuilder sb = new StringBuilder();
Random random = new Random();
int progress = 0;
while(running && progress!=100){
try {
System.out.print(sb.append("#"));
System.out.println(progress+"%");
if (random.nextDouble() * 10 < 2) {
atack.performFight(character,factory.generateRandomEnemy());
}
Thread.sleep(500);
}catch(Exception ex){}
progress = progress+5;
}
}
}
As you can see, I'm using while loop which is supposed to break when running variable is set to false or road is finished. When character dies I call method battleLost:
private void battleLost(Character character){
WorldMap map = new WorldMap();
System.out.println("You are dead.\nWould you like to try AGAIN or LOAD your last save");
System.out.println("Please type AGAIN or LOAD");
while(true) {
String choice = sc.nextLine().toUpperCase();
if (choice.equals("AGAIN")) {
map.running = false;
System.out.println("Create new character?");
break;
} else if (choice.equals("LOAD")) {
map.running = false;
save.readFromFile();
break;
} else
System.out.println("Try again.");
}
}
This method sets running variable in class WorldMap to false, but the while loop is continued instead of breaking. Im aware that problem is probably linked to using map.running = false; in wrong way.
I'd glad if anyone could explain me how this problem should be solved.
boolean running=true;
This variable should be part of Character class.
then, your while will just look like:
while(character.isRunning() && progress!=100)
and, within performFight you can update it to false when died.
I guess battleLost() belongs to PerformAtack class. so the local variable map inside the battleLost() does not affect the object that is controlling the road.
You can do two things:
make running static (and public) and then you can reference it from anywhere by the class name like this WolrdMap.runnning = false but this solution has problems if you decide to do things in parallel (e.g. multiple threads). Remmeber: static data is almost always a pitfall for multi-threaded design!
a better solution is to make atack.performFight return a boolean value and assign that value to the running var: running = atack.performFight(... this is better design in terms of thread safety, but you will have to propagate the boolean value from battleLost() (it too will have to return boolean) to `performFight()' and so on
Well,Change the access modifier for variable boolean running=true; to public static boolean running=true;
once you did that you can change this variable to false without creating an instance in order to break the loop, do something like that
private void battleLost(Character character){
WorldMap map = new WorldMap();
System.out.println("You are dead.\nWould you like to try AGAIN or LOAD your last save");
System.out.println("Please type AGAIN or LOAD");
while(WorldMap.running) {
String choice = sc.nextLine().toUpperCase();
if (choice.equals("AGAIN")) {
map.running = false;
System.out.println("Create new character?");
break;
} else if (choice.equals("LOAD")) {
map.running = false;
save.readFromFile();
break;
} else
System.out.println("Try again.");
}
public void breakTheLoop(){
WorldMap.running=false;
}
because of static is a class variable so it's value will be shared between all classes
I am making a project in which I have a class named runner_HMMPayl from the main of this class I am initiating a JFrame0 f instance. JFrame0 returns the values of text fields in JFrame0 that are then used in main.
I am facing a problem that when I instantiate the JFrame0, it keeps on running and control is not shifted back to main of runner_HMMPayl class. How can I do that?
These are the relevant code snippets.
First one is the main, making JFrame0 instance.
public static void main(String[] args) throws IOException
{
JFrame0 f = new JFrame0();
f.Start(f);
System.out.println("f closed"); //not displayed in console----------
System.out.println("First argument" + args[0]); //not displayed in console-
}
This is the code of the JFrame0 button, which upon pressing should return the arguments.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
argA[0]= "1";
String s1 = jTextField1.getText();
argA[1] = s1;
String s2 = jTextField7.getText();
argA[2] = s2;
// ..
String s7 = jTextField2.getText();
argA[7] = s7;
runner.configureHMMPayl(argA); //function in runner_HMMpayl class (instance:runner)
runner.giveArgs(argA); //function in runner_HMMpayl class
}
I am not able to figure it out.
Use a modal JDialog to stop execution until the dialog is closed.
See How to make Dialogs for more details.
And while you're at it, check out Initial Threads
I am writing a program that will generate a geometry Logic Word Problem, and I am having trouble with it. My goal is to have the program randomly create a word problem that is pre-designed. So far, the program takes input from the user, and then uses that information in the Story methods, somewhat like a game of Mad Libs. Anyways, I want to randomly chose a Story method to run each time the user starts the program. So far this is what I have:
import cs1.Keyboard;
public class LogicProof {
//Main method
public void main () {
System.out.println ("Enter 1. to start.");
System.out.println ("Enter 2. to exit.");
int choice = Keyboard.readInt();
if (choice == 1) { //Take info in and send to createStory
//Randomly run methods
}
if (choice == 2) {
System.out.println ("\nGoodbye.");
}
//Create the first story using inputs from main
private void createStory(String adj,String adj2,String adj3,String action) {
//Use values from main() to create a problem
}
There are two other createStory methods as well. Also, I am going to display the proofs of each problem, and each method has its own proof, so would I be able to then display the proof for the same method, basically just link together the proof method, and story method?
I'm fairly new to Java, and appreciate the help.
Thanks in advance.
To only answer your title, you could use random generation with reflection, but that is in no way how you should solve your current problem.
Don't try and randomly invoke methods. Take a look at java.util.Random's nextInt() and use that to do unique operations based on the value it returns.
This seems like Homework which is why I'm not giving you a full solution here.
public class MadLibs {
public static final String[] STARTERS = { /* ... */ };
public static final String[] ENDINGS = { /* ... */ };
public static String generate(String ... adjectives) {
final Random random = new Random();
final StringBuilder string = new StringBuilder(STARTERS[random.nextInt(STARTERS.length-1)]);
for (String adjective : adjectives) {
string.append(adjective);
string.append(TRANSITIONS[random.nextInt(TRANSITIONS.length - 1)]);
}
return string.toString();
}
}
That's an extremely simple and rough implementation to get you started.
Or maybe, if you have only a few concrete variations:
public class MadLibs {
public static String generate(String ... adjectives) {
int result = new Random().nextInt(MAX);
String madLib = null;
switch (result) {
case 0:
// ...
break;
case 1:
// ...
break;
default:
// ...
break;
}
return madLib;
}
}
Like said above, use random number generation to yourself a 1,2,3,4 ect... Then pass that number into your method as a parameter and then use "if, if else" statements to choose the correct operation to perform. Again, like stated above I will not give any code in case this is indeed a homework problem.
You could generate a Word or Phrase object, populate them into a List.
From there us something like Random or Math.random to pull a word or phrase from the list