Transfer of control from JFrame back to the calling class - java

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

Related

Why am I getting Exception in thread error?

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.

How to use a function from another class in Java? [duplicate]

This question already has answers here:
Java how to call method in another class
(3 answers)
Calling static method from another java class
(3 answers)
Closed 2 years ago.
I know this is a repeated question but I don't really understand how to call upon the functions or the utility of all the privates etc... So what I'm trying to do is "build a bear" where u pick the size and colour in a different class while the main class calls it, like this:
Size
import java.util.Scanner;
public class BABSize
{
public static String size()
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like a small, medium or big bear?");
String size = input.nextLine();
input.close();
return size;
}
}
Colour
import java.util.Scanner;
public class BABColour
{
public static String Colour()
{
Scanner input = new Scanner(System.in);
System.out.println("What colour would u like your bear?");
String colour = input.nextLine();
input.close();
return colour;
}
}
Main
public class MainFunction
{
public static void main(String[] args)
{
BABColour c = new Colourr();
BABSize g = new Size();
System.out.println("Your " + g + "," + c + " bear will be ready in a moment:)");
}
}
Since you are making static functions, you dont need to create instance of those classes and directly call the static methods.
Not suggested but you can still have a call after creating instance of it and using that reference to call the method.
Try to observe what you are returning fron that function and have that reference in calling method.
For example: For asking which beer, you are returning String.
So, in main method have that reference of String.
String beer = BABSize.size();
Similarly for colour you are retuning String so have that in main method.
change it like this
public static void main(String[] args)
{
BABColour c = new BABColour();//here you create a variable of type Colour
BABSize g = new BABSize();
String color = c.Colour();//Here you call the method color
String size = g.Size();//Here you call the method to get the size
System.out.println("Your " + color + "," + size + " bear will be ready in a moment:)");
}
(Im open to any question you have obout this)

Method from another file not being seen

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.

Methods and declaration java

I am trying to make an program to determine averages for school. I am going to have all the files saved to the computer so its easy to access them for multiple uses. I stated to create multiple methods and discovered a problem. I have the user input for a subject in the startup method but in the main method, sub (the subject string) is used and its says "sub cannot be resolved to a variable" I understand why it say this but I am unsure how to fix.
Here is my code:
public class Calculator {
static int x;
static int b;
public static void startup() {
System.out.println("**Receiving User**");
String user = System.getProperty("user.home");
System.out.println("**Checking Directories**");
boolean dir = new File(user + "/Library/Application Support/Average_Calculator/Settings/").mkdirs();
if (dir) {
System.out.println("**Directory Created at:" + user + "/Library/Application Support/Average_Calculator/**");
} else {
System.out.println("**Directory Has Already Been Created at:" + user
+ "/Library/Application Support/Average_Calculator/**");
}
System.out.println("Welcome to the Average Calculator");
System.out.println("Please input the subject average you want to calculate(no caps)");
Scanner scan = new Scanner(System.in);
String sub = scan.nextLine();
// System.out.println(sub);
try {
// System.out.println("It Does!");
FileOutputStream saveFile = new FileOutputStream(
user + "/Library/Application Support/Average_Calculator/" + sub + ".sav");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
FileOutputStream SetsaveFile = new FileOutputStream(
user + "/Library/Application Support/Average_Calculator/Settings/" + "Setting" + sub + ".sav");
ObjectOutputStream setsave = new ObjectOutputStream(SetsaveFile);
// Create an ObjectOutputStream to put objects into save file.
// Close the file.
save.close();
setsave.close();// This also closes saveFile.
} catch (Exception exc) {
exc.printStackTrace(); // If there was an error, print the info.
}
}
public static void main(String[] args) {
startup();
System.out.println(sub);
try {
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream(sub + ".sav");
// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);
x = (Integer) save.readObject();
b = (Integer) save.readObject();
// Close the file.
save.close(); // This also closes saveFile.
} catch (Exception exc) {
// exc.printStackTrace(); // If there was an error, print the info.
}
// Print the values, to see that they've been recovered.
System.out.println(x);
System.out.println(b);
// All done.
}
}
Thanks for the help!
PS I am new to methods and classes, an explanation would be greatly appreciated!
sub is currently a local variable of startup(), so main() does not have access to it.
One solution is to have startup() return the value of sub, and to have main() use that returned value.
A second solution would be to declare sub (and any other shared variables) as a static variable of the Calculator class, which would place it within the scope of both static methods. In this case, you must no longer declare sub locally within startup(), since that would cause the method to ignore the static variable with the same name.
You are declaring sub in your startup method but trying to access it in your main method. The scope of variables declared in methods is limited to that method; that means that once you leave the method, the variable is no longer accessible. If you want to access a variable both methods one option is to make it a property of the class like you did for x and b. Another option is to return the value of sub at the end of your startup method then simply print your call to the method in main.
Here is a good explanation about classes.
Here is a good explanation about methods (you can ignore the part about functions; the explanation for methods is still good).
Your startup function is returning a void. Change this line:
public static void startup() {
to this:
public static String startup() {
and this line:
startup();
to this:
String sub = startup();

None of the print commands produce output, but the program still executes without errors java- eclipse

I'm studying Java and am obviously very new to it. I have what appears to be a working application, however it doesn't produce any output to the console window as expected - it also doesn't give any errors which is baffling. I'm using Eclipse. I would greatly appreciate a second set of eyes to spot out what I'm doing wrong. There is some code in there from trying different approaches to get this to work - which I will delete later.
My question is: Why isn't my program producing output? As a follow up: Why isn't it producing some kind of error since it's not producing output?
I've researched for a couple of days now and the closest I found was this article which although it is similar but it doesn't really apply to this situation.
System.out.print() doesn't send any output to Eclipse console. Why?
*Edited - shortened up the code & add comments on how to fix.
I have 2 classes - Student and Roster.
Roster:
//** client class....*/
import java.util.ArrayList;
import java.util.Arrays;
public class Roster {
/* String copied from the instructions, adding info as the last item*/
static String[] students = {"1,John,Smith,John1989#gmail.com,20,88,79,59",
"2,Suzan,Erickson,Erickson_1990#gmailcom,19,91,72,85",
"3,Jack,Napoli,The_lawyer99yahoo.com,19,85,84,87"};
static ArrayList<Student> studentProfiles = new ArrayList<Student>();
public static void main(String[] args) {
//creating the arraylist - rather, converting a string of arrays to an Array list of student objects
{
for (int i = 0; i < students.length; i++) {
String component = students[i];
String[] terms = component.split(",");
String studentID = terms[0];
String firstName = terms[1];
String lastName = terms[2];
String emailAddress = terms[3];
String age = terms[4];
int grade1 = Integer.parseInt(terms[5]);
int grade2 = Integer.parseInt(terms[6]);
int grade3 = Integer.parseInt(terms[7]);
Student student = new Student(studentID, firstName, lastName, emailAddress, age, grade1, grade2, grade3);
studentProfiles.add(student);
}
}
}
//test just to generate output, didn't work. <-- Moving this inside the main generated the output I needed.
{
System.out.println(studentProfiles);
}
///
/// enter methods here
///
//
}
//other print all attempt
//-->> Put inside main
public static void print_all()
//-->> Put inside main
System.out.println(j);
`enter code here`
//-->> Put inside main
print_all();
print_invalid_emails();
print_average_grade(student);
remove("3");
remove("3");
//}
//}
}
}
You need to put your print inside main method.
The block that you are using:
{
System.out.println(studentProfiles);
}
is called Initializer block and is called when you call the constructor of Roaster.
Try putting the System.out.println(studentProfiles); inside the Main() method.
Also have a look at this:
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Categories

Resources