import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
public class PictureViewer {
final static int MIN_NUMBER = 1;
final static int MAX_NUMBER = 8;
static int image_number = 1;
public static void main(String[] args) {
showMenu();
}
public static int forward(int current_number) {
if (current_number < MAX_NUMBER) {
current_number++;
} else {
current_number = MAX_NUMBER;
}
return current_number;
public static int backward(int current_number) {
if (current_number > MIN_NUMBER) {
current_number--;
}
return current_number;
}
public static String createFileName(int current_number) {
return ("Picture " + current_number + ".jpg");
}
public static String createRandomName() {
return ("Picture " + (int) (Math.random() * 8 + 1) + ".jpg");
}
public static void showMenu() {
PictureViewer theobject = new PictureViewer();
int current_number = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Choose static forward(1), static backward(2),"
+ " createFileName(3), createRandomName(4)");
int user = input.nextInt();
switch (user) {
case 1:
System.out.println("static forward");
current_number = forward(current_number);
theobject.forward();
break;
case 2:
System.out.println("static backward");
current_number = backward(current_number);
theobject.backward();
break;
case 3:
System.out.println("createFileName");
createFileName(current_number);
theobject.showWindow(createFileName(current_number));
break;
case 4:
System.out.println("createRandomName");
createRandomName();
theobject.showWindow(createRandomName());
}
if (image_number != 1);
System.out.println(image_number);
}
}
public void forward() {
if (image_number < MAX_NUMBER) {
image_number++;
} else {
image_number = MAX_NUMBER;
}
}
public void backward() {
if (image_number > MIN_NUMBER) {
image_number--;
}
}
public void showWindow(String filename) {
JFrame frame = new JFrame("GUI Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
What I'm supposed to do:
Write a new function to create and display a GUI window (which I did by doing the showWindow method but I'm not sure how to code the rest of it).
In your switch statement, where you call the methods createFileName() and createRandomName(), add calls to object.showWindow() and pass it the file name the methods return (I added object.showWindow() to those particular methods but I'm getting errors). Test your program, you should be able to go forward and backward with proper behavior when MIN_NUMBER and MAX_NUMBER are reached. When the window is displayed the correct file name should be shown at the top of the frame.
Areas of interest:
Here
case 3:
System.out.println("createFileName");
createFileName(current_number);
theobject.showWindow();
break;
case 4:
System.out.println("createRandomName");
createRandomName();
theobject.showWindow();
and here
public void showWindow(String filename) {
}
First, the compile errors in your program. I copied and pasted your code to my IDE and in the object.showWindow() lines I get compile errors it says:
method showWindow in class PictureViewer cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
To a Java beginner, this may seem cryptic, however it just tells you that the method you are calling, in this case the showWindow() method, is requiring you to pass a String but you are not passing anyting that's why it throws an error. Also, in your question you said
call the methods createFileName() and createRandomName(), add calls to object.showWindow() and pass it the file name the methods return
It is very clear now what to do to remove the compile errors. You need to pass the methods createFileName() and createRandomName(). After doing so, it will look like this:
case 3:
System.out.println("createFileName");
theobject.showWindow(createFileName(current_number));
break;
case 4:
System.out.println("createRandomName");
theobject.showWindow(createRandomName());
Next is the creating and displaying the GUI Window. I will show you how to do this in pseudocode first so you will learn how to do it yourself.
First, add a global variable that we will use to refer to the window. Then, in the showWindow() method:
public void showWindow(String filename) {
if window is null
initialize new window
set the window title using filename
show window
else
set the window title using filename
}
Related
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}
I'm writing a simple Java program.
First, the program asks user to input some info like name and id of the student and uses radio button for asking whether the student is present or absent. After finishing the inputs, then program validate whether predefined student names and inputs are match or not. And check id number again and spit out if input is over 4. Lastly check radio button is true or false. If one of the above two rules get error then program will quit without executing next method.
I have three .java files. One for UI. One for validation and one for storing data.
UI.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UI extends JFrame {
JTextField name = new JTextField("Name", 10);
JTextField id = new JTextField("Id", 10);
JRadioButton attendance = new JRadioButton("Present");
JButton JB = new JButton("Check");
public UI() {
super("Test");
JPanel JP = new JPanel();
JP.add(name);
JP.add(id);
JP.add(attendance);
JP.add(JB);
add(JP);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void buttonAction(){
UI UIbutton = new UI();
UIbutton.JB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == UIbutton.JB) {
String nameInput = UIbutton.name.getText();
int idInt = Integer.parseInt(UIbutton.id.getText());
boolean attInput = UIbutton.attendance.isSelected();
Validate.nameChk(nameInput);
Validate.idChk(idInt);
Validate.attChk(attInput);
Student studentObj = new Student(UIbutton.name.getText(), idInt, UIbutton.attendance.isSelected());
System.out.println(studentObj.name + "'s ID number is : " + studentObj.id + ".");
System.out.println(studentObj.name + " is present: " + studentObj.attendance);
System.exit(0);
}}});
}
public static void main(String[] args) {
buttonAction();
}
}
Validate.java
public class Validate {
public static void nameChk (String nameInput) {
String n1 = "Matthew";
String n2 = "John";
String n3 = "Mark";
String n4 = "Luke";
if ((nameInput.equalsIgnoreCase(n1))||
(nameInput.equalsIgnoreCase(n2))||
(nameInput.equalsIgnoreCase(n3))||
(nameInput.equalsIgnoreCase(n4))){
System.out.println("Your data is okay.");
}
else {
System.out.println("Error, wrong student name.");
System.exit(0);
}
}
public static void idChk (int idInt) {
if (idInt > 4) {
System.out.println("Your id is not correct.");
System.exit(0);
}
else {
System.out.println("Your id is correct.");
}
}
public static void attChk (boolean attInput) {
if (attInput) {
System.out.println("The student is present.");
} else {
System.out.println("The student is absent.");
}
}
}
Student.java
public class Student {
String name;
int id;
boolean attendance;
Student(String name, int id, boolean attendance) {
this.name = name;
this.id = id;
this.attendance = attendance;
}
}
What I want to know is how can I reuse output of that actionlister method somewhere else. Let say I would create foo.java class and use that studentObj variable to give grades like
System.out.println(studentObj.name+"has B+.");
Sort of.
How can I do that? How to turn that variable into global?
This can be achieved in different ways.
Quite simple, but not a good practice would be to create a Singleton. It would contain Students objects and you'll be able to access them from anywhere. Here is example with eager singleton, but you can implement much better versions (check about singleton implementations i.e. here https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples)
public class StudentsSingleton {
private Map<Integer, Student> students = new HashMap<>();
public Student getStudent(int id) { return students.get(id);}
public void addStudent(Student s) { students.put(s.id, s);}
private static final StudentsSingleton instance = new StudentsSingleton();
//private constructor to avoid client applications to use constructor
private StudentsSingleton(){}
public static StudentsSingleton getInstance(){
return instance;
}
}
In that case, you can access it from anywhere by getting the instance :
StudentsSingleton.getInstance().getStudent(id);
A much better solution and a good practice would be to use some Dependency Injection framework i.e. Spring. In that case, you would create a Bean and inject it whenever it is needed to use.
I am trying to write a code that uses a menu to call on a method in a different file that is in the same folder.
import java.util.Scanner;
public class BugTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("==Bug Solution==");
System.out.println("Enter the bug's intial position: ");
int pos = input.nextInt();
Bug bug = new Bug(pos);
System.out.println("--Menu--");
System.out.println("1) Change Directions");
System.out.println("2) Move Bug");
System.out.println("3) Exit");
int menu = input.nextInt();
while (menu != 3) {
switch(menu) {
case 1: turn();
break;
case 2: move();
break;
default: System.out.println("Invalid Response");
break;
}
menu = input.nextInt();
}
}
}
I get an error on case 1 and case 2 saying the method is undefined for type BugTest.
In a main method you should always call methods from a given Object (given that they are not static methods). Otherwise the program doesn't know which object's method it's supposed to call. For example create class Bug:
public class Bug{
public Bug() {
}
public void moveLeft() {
// add code here
}
}
Then in your main method call the method by creating an instance of class Bug:
public static void main(String[] args) {
Bug myBug = new Bug();
myBug.moveLeft() ; // calls the method of the myBug object
}
In your case the problem can be solved by calling bug.turn() and bug.move() instead of just turn() and move().
public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}
we are working on a project trying to make a message in a JOptionPane show up when a button is pressed and certain conditions are met. However whenever the code is activated and a button is pressed, the JOptionPane shows up with no message. Here is the code that creates the GUI
package BlackJack;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BlckJckUI {
public static void main(String[] args) {
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(1000,900);
GUI.setVisible(true);
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 2;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(two);
This is the code that works out the logic.
package BlackJack;
public class Math {
public int cardvalue;
public Math()
{
Arrays array = new Arrays();
if (array.clicktracker == 1)
{
array.dealer = cardvalue;
array.result = "Please select the first card you have :)";
}
else if (array.clicktracker == 2)
{
array.playerhand.add(cardvalue);
array.result = "Please select the second card you have :)";
}
else if (array.clicktracker >= 3)
{
array.playerhand.add(cardvalue);
if (array.playerhandtotal <= 8)
{
// array.result = result statement
array.result = "You should just hit until you're safe. If the dealer 6 or below,\n"
+ " the chances are that he'll bust and if not, remain low above 17.\n"
+ " As long as you can pull a 17 or higher, you should be safe. Pick \n"
+ "another card or reset.";
This is the code that creates the Array and variables associated with it.
package BlackJack;
import java.util.ArrayList;
public class Arrays{
public String result = null;
ArrayList<Integer> playerhand = new ArrayList<Integer>();
public int dealer = 0;
public int clicktracker = 0;
public int playerhandtotal = 0;
{
for (int element: playerhand)
{
playerhandtotal = element + playerhandtotal;
}
System.out.println(result);
System.out.println(dealer);
System.out.println(clicktracker);
}
}
In your Math constructor, you are changing the result of a different type of array.result than the one you are trying to display.
I would consider passing the Arrays instance into the Math constructor so that you can modify the result from there. Be sure to not reassign the instance though.
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math(array);
math.cardvalue = 2;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
...
public Math(Arrays array)
{
if (array.clicktracker == 1)
{
// And so on ...
The problem is that you are creating two separate instances of your Arrays class. Once in the actionPerformed method and also within the constructor of your Math class.
This code you currently have:
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 2;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
will display the result of the Arrays object you created in the actionPerformed method - which is null as the result of this object is initialised to null and never set.
This has been mentioned in other answers and comments and will solve it from producing null but this approach will now always yield the same result as you are still always creating a new instance of your Arrays class in your actionPerformed method.
A better approach would be to separate the logic of the result from the constructor of your Math class into another method and create this instance of your Math class outside of the actionPerformed method. Then within your actionPerformed method call your method which will do the logic for your result.
In UI:
Math math = new Math();
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
math.cardvalue = 2;
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
In Math:
public class Math {
public int cardvalue;
public Arrays array;
public Math()
{
array = new Arrays();
}
public void calcResult(){
if (array.clicktracker == 1)
{
//...rest of your logic
}
}