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();
}
}
Related
I'm new to JAVA programming, and was wondering if it's possible/how to ask the user to input what class they'd like to run and then call/run that class?
Example:
I created two classes to solve the Towers of Hanoi given (supplied by user) n amount of disks. One class solves the puzzle recursively and the other class solves the puzzle iteratively. When I am asking the user for the number of disks they'd like to use, is it possible to ask them how they would like to solve the program whether it be recursively or iteratively and then call the class that they chose?
Yes, that is possible.
This version may look a bit more complicated on first glance, but it separates the parts more clearly. The interface and the classes would usually be in separate files in real applications. Also, the static chooseSolver - method would possible be moved to a separate class named something like SolverFactory.
import java.util.Scanner;
import java.util.Set;
public class Main {
interface Solver {
void solveIt();
}
static class SuperSolver implements Solver {
public void solveIt() {
System.out.println("SuperSolver always solves anything");
}
}
static class FastSolver implements Solver {
public void solveIt() {
System.out.println("Noone beats the FastSolver");
}
}
public static void main(String[] args) {
String in = askUserForOption();
Solver s = chooseSolver(in);
s.solveIt();
}
private static String askUserForOption() {
String in;
Set<String> validOptions = Set.of("A", "B");
try (Scanner sc = new Scanner(System.in)) {
do {
System.out.print("Enter A or B: ");
in = sc.nextLine();
} while (!validOptions.contains(in));
}
return in;
}
private static Solver chooseSolver(String in) {
switch (in) {
case "A":
return new SuperSolver();
case "B":
return new FastSolver();
default:
throw new IllegalArgumentException("something went terribly wrong - an invalid option was given");
}
}
}
You can do this in a pretty straightforward manner using a common interface both solvers implement.
interface HanoiSolver {
void solve(int n);
}
// iterative solver
class IterativeHanoi implements HanoiSolver {
public void solve(int n) { ... }
}
// iterative solver
class RecursiveHanoi implements HanoiSolver {
public void solve(int n) { ... }
}
public class MainClass {
public static void main(String[] args) {
// you can change this to read input however you like
String userInput = args[0];
Integer n = Integer.parseInt(args[1]);
HanoiSolver solver;
if (userInput.equals("recursive")) {
solver = new RecursiveHanoi();
} else {
solver = new IterativeHanoi();
}
solver.solve(n);
}
}
Depends on where this code is used internally or as library package.
Internally you can use interface and then seperate out the concrete implementation.
In library , you can again let user call interface method , write implementation of that interface based on condition.
Or if you want the user to determine the algo to use during the runtime then use Reflection to decide which class's object to create.
I was trying to review some of the Java language using a spark chart I had once bought. Regarding the use of anonymous inner classes they give this example :
Dice rollDice() {
return new Dice() {
int number = (int)( Math.random() * 6 ) + 1;
};
}
Problem is, I do not see how this would work, and can not get the compiler to accept it as a method within another class. The compiler complains about each reference to Dice "symbol can not be found."
Am I not understanding their example correctly or is this completely invalid code? Thanks in advance!
p.s. if this is working code, could someone provide me with an example of how it can be used?
Edit: I have found something that finally makes sense
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
This above code is passed to a method that takes an instance of Superclass or completely implements the Interface. For instance, a method that has an EventHandlerparameter and we have not already defined a class that implements the handle(ActionEvent e) method.
enlargeButton.setOnAction(
new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
});
In this way, it will truly be anonymous. I think the example given in Java's own tutorial to be very poor.
It looks like you've mostly answered your own question and you will probably want to go through some full tutorial or documentation to understand things fully, but here are some answers to your immediate questions.
Your first sample code wont compile until you have a Dice class or interface you can extend. So as an example you can get this code to compile:
class Dicey {
interface Dice {
}
Dice rollDice() {
return new Dice() {
int number = (int) (Math.random() * 6) + 1;
};
}
public static void main(String... none) {
Dice dice = new Dicey().rollDice();
// dice.number; <-- not available
}
}
Now you can do this, but as you suspect this is not a very useful things to do (for a few reasons) but the biggest problem is that after you create this anonymous instance there isn't really a way to get to the .number member.
More usually you would have an anonymous subclass implement some methods on the interface, so that you can actually do something with it. So for example
class HelloAnonymous {
interface Hello {
String say();
}
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
// prints 'world'
}
}
gives you a way of making fantastically useful Hello objects that can say something. Having said all this, writing anonymous inner classes is fairly old school because functional interfaces now largely replace the need for them. So in this example you could have:
class HelloAnonymous {
#FunctionalInterface
interface Hello {
String say();
}
// old school
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
// with lambda notation
Hello alsoHello(String world) {
return () -> {
return world;
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
System.out.println(new HelloAnonymous().alsoHello("world").say());
}
}
since I don't know about 'Dice' class I cannot write same method but I try some thing similar to that. It compile and work can access 'number' variable by using reflection. My opinion is it is not very useful. Following is my code:
public class TestClass {
public static void main(String a[]){
TestClass aClass = rollDice();
try {
System.out.println("value of number : " + aClass.getClass().getDeclaredField("number").getInt(aClass));
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
static TestClass rollDice() {
return new TestClass() {
int number = (int) (Math.random() * 6) + 1;
};
}
}
That example is extremely broken. Throw that source away. Try this:
import java.util.Random;
public class DieFactory {
interface Die { int roll(); }
static Die create(long seed) {
Random random = new Random(seed);
return new Die() {
#Override
public int roll() {
return random.nextInt(6) + 1;
}
};
}
// Now you can roll 2 dice pretty easily.
public static void main(String [] args) {
DieFactory.Die die1 = DieFactory.create(42);
DieFactory.Die die2 = DieFactory.create(24);
for (int i = 0; i < 40; i++) {
System.out.println(die1.roll() + die2.roll());
}
}
}
Incidentally, the word "dice" is plural for the singular "die."
How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.
I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.
I have the following piece of code. I do not understand why its not working.
I'd really appreciate help on this.
import java.util.Scanner;
import java.io.*;
class ReadFiles {
String [] codes = new String[99];
int i = 0;
private Scanner readCodes;
public void openCodesFile() {
try {
readCodes = new Scanner(new File("C:/Users/Carlo/Desktop/Files/codes.txt"));
} catch (Exception e) {
System.out.println("Could not locate the data file!");
}
}
public void readCodesFile() {
while(readCodes.hasNext()) {
codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
}
}
public void closeCodesFile() {
readCodes.close();
}
}
class NewHardware {
public static void main(String[] args) {
ReadFiles codesRead = new ReadFiles();
codesRead.openCodesFile();
codesRead.readCodesFile();
codesRead.closeCodesFile();
}
}
The output prints out "null" a bunch of times.
Also, I want to be able to not only print out the codes but use the codes array in the class NewHardware and manipulate it (print it out, truncate it, etc).
I was thinking of doing the following with readCodesFile():
public String readCodesFile() {
while(readCodes.hasNext()) {
codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
}
return (codes[i]);
}
Or something but it hasn't worked just yet. Am I on the right track?
Oh, just wanted to add that the text contains the following:
G22
K13
S21
I30
H15
N23
L33
E19
U49
EDIT:
Thanks to Tony and Churk below to help me with my idiocy. I am accepting Tony's answer basically because he challenged me to think but Churk's answer is just as valuable.
For the second part of my question (where I asked about being able to use it in class NewHardware), I did the following:
class NewHardware {
public static void main(String[] args) {
ReadFiles codesRead = new ReadFiles();
codesRead.openCodesFile();
codesRead.readCodesFile();
for (int i = 0; i < 9; i++) {
System.out.println("\n\n" + codesRead.codes[i]);
}
codesRead.closeCodesFile();
}
}
This is of course not the final program code but this has helped me get the basic idea. Hope this helps others too.
codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
You are printing codes[i++]
Look carefully at your readCodesFile() method. Look at every line. What is it doing? Can you explain it to us?