I am new to java. Working in the book titled starting out with java from control structure through objects.
My assignment is as followed: create a class method that accepts a charge account number as its argument. The method should determine whether the number is valid by comparing it to the following list of valid charge account numbers:
5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152,
4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231,
3852085, 7576651, 7881200, 4581002\
These numbers should be stored in an array or an ArrayList object. Use a sequential search to locate the number passed as an argument. if the number is in the array, the method should return true, indicating the number is valid. if the number is not in the array, the method should return false, indicating the number is invalid.
My question goes along, is the program I have enough, or do I have to create a separate class?
the problem i'm having is this chapter seems different from the previous. we just got done with chapter 6 which was classes and that required me to make a main project and a constructor. my question is, are arrays just one program? or am i missing something. the program seems to run okay. if you could clear this up for me that would be awesome.
My question is: in chapter 6, I had to create two programs. One the main and second the class for example. One was the constructor, the other was the main in which it spoke to the constructor.
Do arrays require two programs or is the program I wrote sufficient enough?
the program code is
import java.util.Scanner;
public class ChargeAccount {
static int[] validChargeAccountNumbers = {
5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152,
4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231,
3852085, 7576651, 7881200, 4581002
};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// ask the user for an account number
System.out.print("Enter the account number: ");
// get the number from the user
int number = in.nextInt();
// check to see if the number is valid
if (ChargeAccount.isValid(number) == true)
{
System.out.println("Fraud account detected.");
} else
{
System.out.println("That number is invalid.");
}
}
public static boolean isValid(int number) {
for (int i = 0; i < validChargeAccountNumbers.length; i++) {
//checks if the numbers were in the list
if (validChargeAccountNumbers[i] == number) {
return true;
}
}
return false;
}
}
I apologize if any formatting is wrong. please ask me any questions.
As he said it is nothing to with learning Object Oriented Programming.
It is all about our how effectively we designed the code.
The above answer is perfectly fine, place the business logic code in one class ChargerAccount.java
And Create the rest of the code in another class to test the logic.
So it seems like this has to do with learning Object Oriented Programming.
In this case, you would have one file, ChargeAccount.java, which would contain that code, and maybe ChargeAccountTest.java, which would contain the rest of the code.
In OOP, constructors instantiate objects, like you did with the Scanner object, calling new Scanner() called the Scanner constructor. Research how to create constructors and how to call them in other classes.
public static void main(String[] args)
{
ChargeAccount account = new ChargeAccount();
//rest of code
}
Related
I am trying to make a hangman game as follows:
public void guessLetter(String letter) {
HashSet<String> guessedLettersA = new HashSet<>();
guessedLettersA.add(letter);
for (String guessedLetterA : guessedLettersA) {
this.guessedLetters += guessedLetterA;
}
if (!this.word.contains(letter)) {
this.numberOfFaults++;
}
}
public boolean letterCheck() {
if ( = false ) {
System.out.println("You have already guessed this letter!");
}
I am currently working in the letterCheck method and want to see if one of the inputs is a repeat and let the user know that their guess doesn't count. I assume it wont make up their failures or count as another guess because it is never added to the hashset. So where I am struggling with, is how do I do as I want, I was thinking of using the built-in way a hashset returns false to detect this, but I have no idea how to implement this since it needs to refer to another method and I don't know how to make a string hashset return booleans. I would greatly appreciate any help at all, thanks.
The add API would return false for an existing value(that it cannot add to the Set), so your condition can be dealt with
boolean letterCheck = guessedLettersA.add(letter);
if(!letterCheck) {
System.out.println("You have already guessed this letter!");
}
Note: The invocation of this block is solely dependent on the design of your application.
I am very new to Java, so sorry if this is stupid and obvious or worded poorly. I don't really know enough yet to know what I don't know.
So I decided that since I have to learn Java, I'd just jump in head first and try to figure it out as I go. So far, it's worked decently. I'm trying to reinforce some basic concepts I already know by writing small programs that do trivial stuff.
I decided I'd write a little text based adventure game and it's working well so far. I'm using Scanners and Switches to call methods that use Scanners and Switches to call other methods. That's all working fine.
So far it's a very linear straight line, like an old choose your own adventure book. But, I wanted to add a player inventory. I have a very vague idea of how to do it, but I have a pretty solid idea of what I want it to do.
So, basically I want to store a piece of information that says the player has a specific item. I want to be able to test for the presence of more than one item at once. And I want to be able to tell the player what items he has at any point in the game.
I don't really know how to ask the question better.
My best guess is doing something like
int key, potion;
key = 0
potion = 2
and then testing the values of each one
if (key = 0) {
System.out.println("you don't have the key ");
}
if (key > 0) {
System.out.prinln("You unlock the door");
}
I'm doing each new room as a separate method, so the whole game is just a big chain of methods. So my hope is that the information about items can be stored in a separate method that I can access through switches or if/else in the current room method the player is in. So, the player is unlocking a door in room2, which is its own method, and he picked up the key in room1, which is its own method, and the key is stored as an integer in the inventory method. But the key was one use, so the key integer is set to 0 and the method room3 starts. If that makes any sense.
Again, sorry if this is really stupid basic stuff. I'm very new to programming.
No problem and I applaud you for choosing to learn programming. This is basic data structures. If you want to hold a value, in most programming languages, you'll have an array. I think breaking your logic down is a good idea i.e., (store an item, test for > 1, list items). The first step is making this as simple as possible and than maybe adding getters/setters later through refactors. Ultimately, your goal is to make the most basic code work first (like this) and than refactoring towards an object oriented class with getters/setters and/or a HashMap.
1:
public class PlayerInventory
{
private String[] inventoryStr = new String[20]; // basic implementation
inventoryStr[0] = "Phone";
inventoryStr[0] = "Book";
}
2:
int arrayLength = inventoryStr.length;
3:
for(int i=0; i < inventoryStr.length; i++) {
System.out.println( inventoryStr[i] );
}
Refactor (after you write unit tests for this)
1*: (with a list)
import java.util.*;
import java.util.*;
public class CollectionGetterSetter {
private List<String> playerInventory;
public void setPlayerInventory(List<String> inv) {
this.playerInventory = inv;
}
public List<String> getPlayerInventory() {
return this.playerInventory;
}
public static void main(String[] args) {
CollectionGetterSetter app = new CollectionGetterSetter();
List<String> PlayerInventory = new ArrayList();
PlayerInventory.add("phone");
PlayerInventory.add("book");
PlayerInventory.add("glasses");
PlayerInventory.add("nav");
app.setPlayerInventory(PlayerInventory);
System.out.println("Player 1: " + PlayerInventory);
List<String> PlayerInventory2 = new ArrayList();
PlayerInventory2.add("cap");
PlayerInventory2.add("gown");
PlayerInventory2.add("foo");
PlayerInventory2.add("bar");
}
}
So I have written a Java program that has a function handInExam() that may not be called twice in a row, thus the program is history-sensitive. The problem that then occurs is that I need a variable canHandInExam to check whether this method has already been called and update this variable in each method, which leads to very poor maintainability. Below is a code snippet to show the problem.
public class NotAllowedException extends Exception {
public NotAllowedException(String message) {
super(message);
}
}
import java.util.Scanner;
public class Exam {
String[] exam;
String[] answers;
boolean canHandInExam;
public Exam(String[] questions) {
exam = questions;
answers = new String[exam.length];
canHandInExam = false;
}
// This method may only be called once in a row
public void handInExam throws NotAllowedException() {
if (canHandInExam) {
// Send exam to teacher
canHandInExam = false;
} else {
throw new NotAllowedException("You may not hand in this exam!");
}
}
public void otherMethod() {
// Do something
canHandInExam = true;
}
}
In this small example it is feasible to slightly adapt each method, however if you would have lots of methods you would need to adapt all of them. Since after all these methods you may again call handInExam() thus the variable canHandInExam would need to be set to true.
Is there a way to solve this problem in a way that is more maintainable? I am open to other possible programming languages that are not OO, but at this point I am unsure of what would be suitable.
I have considered using functional programming (e.g. Haskell) as those languages are not history-sensitive, however I did not know how to limit that you may only call a function once in a row. I tried searching for how to limit a function call to n times in a row both in Java and Haskell, but this ended up with only references to how to call a function n times.
If you speak about handing in an exam, than this doesn't mean that something is done with that exam, but that there is some entity to which the exam is given. So instead of storing within the exam whether it was handed in or can be handed in, something like this would be more appropriate:
//or whatever you call this
public interface Institution {
void handInExam(Exam exam) throws DuplicateExamException;
boolean isHandedIn(Exam exam);
}
Implementations of Institution store the exams that were handed in (possibly using a Set).
I'm working on a program that will allow a user to use a console menu to input various things into an array.
Input instances of the class student into the array which I have done and works.
Create instances of course details which I have also done.
And search the array for a particular students details. If a student with this name exists, it will print all of their details that are stored in the array and if not will throw up a message saying something like "Student not on Course".
I'm just assuming student names are unique as I only need to store 20 of them. I have created this method so far which doesn't seem to be working. I think I need to use a for loop instead of binarySearch but I'm not quite sure how to do that as no videos or posts seem to show how to use this loop with a String and a Scanner.
This is the method so far:
public static void Search()
{
String studentName;
#SuppressWarnings("resource")
Scanner searchScanner = new Scanner(System.in);
System.out.println ("Type Student Name to Search");
studentName = searchScanner.nextLine();
int FoundName;
Arrays.sort(Students);
FoundName = Arrays.binarySearch(Students, studentName);
if (FoundName > -1)
{
System.out.println("FoundName is" + Students[FoundName]);
} else
{
System.out.println("Student not found");
}
}
Any help with this would be greatly appreciated, you would be helping a lowly noob out very much :)
If you prefer to do a sequential search, you can use a for loop like this:
private void Search(){
// Create a scanner for input, and get the name for search
Scanner inputScanner = new Scanner(System.in);
System.out.println("Type student name for search:");
String studentName = inputScanner.nextLine();
// use for loop to search array.
for(int i = 0; i < studentArray.length; i++){
if(studentArray[i].getName().equals(studentName)){
// If student was found, print his details and return from this function.
System.out.println(studentArray[i]);
return;
}
}
// If we reach this point, it means the student was never found in the for loop.
System.out.println("Student not found.");
}
A couple things to note:
In your question, you're comparing a student object with a string. The difference in types alone is enough to make the binary search return false, so you will never get a match.
In my loop, I am assuming the array holds Student objects, so I call getName() on the student object to compare the two strings, so I will get a match if one exists.
Printing the student object itself will not just print values, you need to override toString() if you haven't yet.
First of all don't do the SuppressWarnings. It's a bad practice and not good when you are beginning to learn to start with bad practices.
I would use instead of the binarySearch for your case, just use the contains method in a list, like this:
List <String> list = new ArrayList();
list.add("one");
list.add("two");
if (list.contains("two")) {
System.out.println("true");
}
In addition no need to sort the array : ).
Just a question from a noob: how do I avoid huge main (in case of JavaFX, start) methods? I tend to create one-class projects but I know that's incorrect. Basically I do not know when to create dedicated classes for specific tasks.
I hope this question is not so stupid.
It's a not a stupid question. From what you've said, you might not need other classes. You may just need methods.
Lets look at a simple example:
public class MyClass {
public static void main(String[] args) {
int i = 4 + 2;
System.out.println(4 + 2);
}
}
Easy, right? But now, what if it gets harder.
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int k = i + (7 / 2) * 3 / 14;
System.out.println(i + " " + k);
}
}
}
Now obviously, this isn't actually harder. But notice how there is a pattern? We take every number 0-9, and add (7 / 2) * 3 / 14. This can be moved into a method:
int getNumber(int i) {
return i + (7 / 2) * 3 / 14);
}
Now, our code looks much cleaner, as we don't have to deal with any addition or division or multiplication
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int k = getNumber(i);
System.out.println(i + " " + k);
}
}
}
This example might seem dumb, because it involves a very easy math problem, but the point is: If you have something that you do repeatedly, put it in a method.
Note:
Methods can also be used to split up a large function. When in doubt, divide and conquer!
See this:
void run() {
getInput();
tick();
render();
}
Is much cleaner than something like this:
void run() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
String string = reader.nextString();
MyObject obj = new MyObject();
obj.doSomething(string);
obj.render();
}
If you looked at that code you'd have no idea what it was doing! But the first example you would, because it divides into methods that clearly identify what they do.
Anyway, about classes:
Google OOP! There are tons of great resources. For most classes, you can think of them as a container. You could create a class, Wallet, that would contain Coins and manipulate it (think spend, remove, add).
There is no stupid question :)
You ask about Oriented Object Programming concept.
In Java, C++ or Php Object, the purpose is to store your code into logical aera. Immagine your code like life. Immagine everything act like an object.
For example, your program is simulating car.
In your code you will have an class Car, then a class Engine, then class BMW that inherit from Car and Car who is containing a instance of Engine.
In internet (use google) you will find a lots of explanation about how OOP work. All of this will explain this much better than i will.
If you have any question, you are welcome :)
This is my opinion that I've developed over the course of learning to program. Though my background is moreso with perl scripting and not oop
Separate the presentation from the data/logic.
Meaning, everything should be in classes (or function), and from the main thread you merely pass the object (or function) data, and you get data the same way.
If it does a specific set of tasks, make a class out of it.
If it could be used for other purposes make a class out of it.
If it does a specific operation, make a function out of it.