Identify an item from array? - java

I have 3 arrays, working parallel. I need to give the user the ability to identify an item from the array, and remove it and its information, and or edit its information.
This is what I have so far:
private static int identifyComputer(String[] computerBrand, double[] computerSpeed, double[] computerPrice) {
Scanner keyboard = new Scanner(System.in);
int counter = computerBrand.length;
System.out.println("Computer brand?");
String cb = keyboard.nextLine();
int i = 0;
boolean notFound = true;
for (i = 0; i < counter && notFound; i++)
{
if (cb.equals(computerBrand[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound = false;
}
if (notFound) {
return -1;
}
else
{
System.out.println("Computer Speed?");
String cs = keyboard.nextLine();
boolean notFound2 = true;
for (i = 0; i < counter && notFound2; i++)
{
if (cs.equals(computerSpeed[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound2 = false;
}
}
if (notFound) {
return -1;
} else {
System.out.println("Computer Price?");
String cp = keyboard.nextLine();
boolean notFound3 = true;
for (i = 0; i < counter && notFound3; i++)
{
if (cp.equals(computerPrice[i]))
{
System.out.println(computerBrand[i]);
System.out.println(computerSpeed[i]);
System.out.println(computerPrice[i]);
notFound3 = false;
}
}
if (notFound) {
return -1;
}
}
}
}
return i;
}
But I know that isnt how you do it 100%. It has some errors on the for loops and it doesnt work correctly. I was trying to get the user to be able to indentify the computer and return the index of that computer. But I am also unsure of that too.
(I CANNOT USE ARRAYLISTS)

It's confusing to store the information in three arrays in parallel. I strongly recommend you create a new type of object with all the information, and create a single array of that object:
class Computer {
String brand;
int speed;
double price;
}
Next, create an array of Computer objects and manipulate the variables in class Computer through that array. Your code will be much easier to write.

Related

Java objects and 2D arrays

I am working on my A-Level computing project, and I have a 2D array, with in the x direction name, password, state (just a variable). I want to sort the 2D array using a bubble sort so that I can implement a binary search on the data. Here is the code I have come up with:
public String[][] sort(String[][] details, int len){
boolean flag = false;
String[] temp = new String[3];
int z=0;
do{
flag = false;
for (int i = 0; i < len; i++){
if(details[0][i].charAt(0) > details[0][i + 1].charAt(0)){
flag = true;
temp[0] = details[0][i];
temp[1] = details[1][i];
temp[2] = details[2][i];
details[0][i] = details[0][i + 1];
details[1][i] = details[1][i + 1];
details[2][i] = details[2][i + 1];
details[0][i + 1] = temp[0];
details[1][i + 1] = temp[1];
details[2][i + 1] = temp[2];
}
}
len--;
} while (flag);
return details;
}
However it has sort of come to my attention I could do this much easier using object orientation which is something I would love to try and have a go at. Does anyone know where I could start learning about object orientation in this sort of context, the guides I have searched for online, just talk about shapes etc... and I am really not sure how to implement those guides into this situation.
From my understanding, what I could do is set up an object with three variables, name, password and state; and when I called upon a name, I could also get the details for the password and state. Am I along the right lines here? and if so can anyone show me how I can do this please.
Thanks a lot.
Sam
edit -
Thanks for all the help guys, thanks to this, I have worked out how to implement this in my project, and it is amazing how much easier it makes the code! Thanks a lot!
For anyone else struggling with this problem, this is my final code:
public class loginDetailsOO {
public static void main (String[] args){
loginDetailsOO object = new loginDetailsOO();
object.run();
}
public void run(){
String password = encrypt("password");
String location = "textFiles\\PasswordScreen.txt";
int lines = numberOfLines(location);
User[] user = fileToArray(location, lines);
int index = searchForUsername(user, lines / 4, "VELINGUARD");
if (password.equals(user[index].getPassword())){
System.out.println("entrance is granted");
}
User u = new User("ball", "pass", 0);
addToFile(u, "VELINGUARD");
}
public void addToFile(User newUser, String currentUsername){
String location = "textFiles\\PasswordScreen.txt";
newUser.setUsername(newUser.getUsername().toUpperCase());
int lines = numberOfLines(location);
User[] user = fileToArray(location, lines);
int line = lines / 4;
int index = searchForUsername(user, line, currentUsername);
if (user[index].getState() == 1){
if (searchForUsername(user,line, newUser.getUsername()) == -1) {
newUser.setPassword(encrypt(newUser.getPassword()));
user[line] = newUser;
user = sort(user, line);
writeToFile(location, user, line);
} else {
System.out.println("User already exists");
}
} else {
System.out.println("Permission not granted");
}
}
public User[] sort(User[] user, int len){
boolean flag = false;
User temp;
int z=0;
do{
flag = false;
for (int i = 0; i < len; i++){
if(user[i].getUsername().compareTo(user[i + 1].getUsername()) > 0){
flag = true;
temp = user[i];
user[i] = user[i + 1];
user[i + 1] = temp;
}
}
len--;
} while (flag);
return user;
}
public String encrypt (String password){
String encrypted = "";
char temp;
int ASCII;
for (int i = 0; i < password.length(); i++){
temp = password.charAt(i);
ASCII = (int) temp;
if (ASCII >= 32 && ASCII <= 127)
{
int x = ASCII - 32;
x = (x + 6) % 96;
if (x < 0)
x += 96; //java modulo can lead to negative values!
encrypted += (char) (x + 32);
}
}
return encrypted;
}
public String decrypt (String password){
String decrypted = "";
char temp;
int ASCII;
for (int i = 0; i < password.length(); i++){
temp = password.charAt(i);
ASCII =(int) temp;
if (ASCII >= 32 && ASCII <= 127)
{
int x = ASCII - 32;
x = (x - 6) % 96;
if (x < 0)
x += 96;
decrypted += (char) (x + 32);
}
}
return decrypted;
}
public User[] fileToArray(String file, int lines) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
int line = lines / 4;
String temp[] = new String[3];
User[] user = new User[line];
for (int i = 0; i < line; i++){
temp[0] = reader.readLine();
temp[1] = reader.readLine();
temp[2] = reader.readLine();
reader.readLine();
user[i] = new User(temp[0], temp[1], Integer.parseInt(temp[2]));
}
return user;
} catch(Exception e){
System.out.println("File not found");
return null;
}
}
public void writeToFile(String location, User[] user, int length){
try {
File f = new File(getClass().getResource(location).toURI());
f.setWritable(true);
FileWriter w = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(w);
wipeFile(f);
for (int i = 0; i <= length; i++){
writer.write(user[i].getUsername());
writer.newLine();
writer.write(user[i].getPassword());
writer.newLine();
writer.write(user[i].getState());
writer.newLine();
writer.write("-");
writer.newLine();
}
writer.close();
f.setReadOnly();
} catch(Exception e){System.out.println("error writing to file");}
}
public void wipeFile(File f) {
try {
PrintWriter wiper = new PrintWriter(f);
wiper.println("");
} catch (Exception ex) {
System.out.println("error wiping file");
}
}
public int searchForUsername(User[] user, int lines, String name){ //implements binary search
int low = 0;
int high = lines - 1;
int mid;
while (low <= high){ //by using a while loop it means if it is an empty file than there will be no issue
mid = low + high;
mid = mid / 2;
if ((int) name.charAt(0) > (int) user[mid].getUsername().charAt(0)){
low = mid + 1;
} else if ((int) name.charAt(0) < (int) user[mid].getUsername().charAt(0)) {
high = mid - 1;
} else {
if (user[mid].getUsername().equals(name)){
return mid;
}
else {
int pass = 0;
do{
if (user[mid - pass].getUsername().equals(name)){
return mid - pass;
} else if (user[mid + pass].getUsername().equals(name)) {
return mid + pass;
}
} while (true);
}
}
}
System.out.println("Name not found");
return -1;
}
public int numberOfLines(String file) {
try{
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(getClass().getResourceAsStream(file)));
lnr.skip(Long.MAX_VALUE);
int length = (lnr.getLineNumber() + 1); //Add 1 because line index starts at 0
lnr.close();
return length;
}catch(Exception e){
System.out.println("File not Found");
return 0;
}
}
and:
public class User{
private String username;
private String password;
private int state;
public User(){
username = "";
password = "";
state = 0;
}
public User(String user, String pass, int st){
username = user;
password = pass;
state = st;
}
public void setUsername(String name){
username = name;
}
public void setPassword(String pass){
password = pass;
}
public void setState(int st){
state = st;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public int getState(){
return state;
}
Bubble sort is meant to be used in only one context in Computer Science, as an example of how simple approaches can sometimes be the worst approach. If you don't remember anything else about sorting, remember that you should never use bubble sort (quicksort is almost always a safer bet).
In order to do this with object orientation, you need objects. These are the code equivalent of which "nouns" are going to be describing the problem. This might mean you would need (minimally) a:
List
Entry
Comparison (Thing)
The problem is that the ordering of something is an action (a verb) and not typically a noun. However, we can make it a noun (thank you English for having "gerunds"). This adds:
Sorter (an interface)
BubbleSorter (ick, yuck, boo!)
QuickSorter
HeapSorter
The main problems come into play when one realizes that without information hiding you don't have much in the way of Object-Orientation. To do this many of the items would require their data being private, and it is something of a try a few times to find the right balance between the "data structure" approach of all exposed data and the OO approach of all private data.
A very pure OO-approach might look like:
class Book extends Entry {
public String getTitle() {
...
}
}
List<Book> books = new List<Book>();
books.add(new Book(...));
books.add(new Book(...));
books.add(new Book(...));
Sorter sorter = new QuickSorter();
Comparison<Book> byTitle = new Comparison<Book>() {
public int compare(Book one, Book two) {
return String.compare(one.getTitle(), two.getTitle());
}
}
sorter.sort(books, byTitle);
Of course, there are different things that people value, and so they might come up with valid, but entirely different OO structures.
Finally, there is already a very good OO-ish set of data structure in java.util, and while it may be fun to create a new one, one should use the java.util.List and friends because they already implement the fastest sorting algorithms (in Collections.sort) and most other libraries expect a java.util.List and not a my.custom.List.
Have fun, and happy hacking!
Make a Detail class that stores the details you are currently storing in an array. Something like:
public class Detail {
public String name;
public String password;
public String state;
}
Then modify your existing code to work with Detail objects instead of arrays of arrays.
public Detail[] sort(Detail[] details){
boolean flag = false;
do{
flag = false;
for (int i = 0; i < details.length; i++){
if(details[i].name.compareTo(details[i + 1].name) > 0){
flag = true;
Detail temp = details[i];
details[i] = details[i + 1];
details[i + 1] = temp;
}
}
len--;
} while (flag);
return details;
}
Note that it would be even better to just use a library function to sort the array, but if you want to do it this way to learn about bubble sort, that's fine.
You will probably need to modify the other parts of your code to use Detail objects as well.

I'm getting a java.lang.NullPointerException: null error and I don't know what is missing [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
I think this part may be the reason I'm getting the NullPointerException error, but I don't know what I'm missing. I have put my full code for the program below just in case there is something that is wrong with that that is giving me that error message.
//client class
public class Downsize
{
public static void main (String [] args)
{
System.out.print("Do you want to downsize the company? (Y/N): ");
String dummy = APIO.getString().toUpperCase();
while (dummy.equals("Y"))
{
Employee employee = new Employee();
System.out.print("Do you want to downsize the company? (Y/N):
dummy = APIO.getString().toUpperCase();
}
}
}
//object class
public class Employee
{
int numEmp;
int sprayer;
int winner;
boolean [] employees;
public Employee()
{
System.out.print("How many employees? (0 to end): ");
int numEmp = APIO.getInt();
System.out.print("Who gets the spray can first?: ");
int sprayer = APIO.getInt();
FillArray();
Selection();
Winner();
}
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
public void Selection()
{
System.out.println("EM="); //debugging method
for (boolean em: employees)
{
System.out.println(em);
}
int complete = numEmp;
while (complete > 1)
{
System.out.print("spraycan passed to #" + sprayer);
if ((sprayer + 1) > numEmp)
{
sprayer = 0;
}
while (employees[sprayer + 1] == false)
{
sprayer++;
if (sprayer >= numEmp)
{
sprayer = 0;
}
}
employees[sprayer + 1] = false;
System.out.print(" - sprays #" + (sprayer + 1) + "'s hair");
complete--;
sprayer++;
while (employees[sprayer] == false)
{
sprayer++;
if (sprayer > numEmp)
{
sprayer = 1;
}
}
}
}
public void Winner()
{
if (sprayer == 0)
{
sprayer = 1;
System.out.print("\nThe Winner is #" + sprayer);
System.out.print("\n");
}
}
}
//stack trace for the error message
java.lang.NullPointerException
at Employee.FillArray(Employee.java:22)
at Employee.<init>(Employee.java:14)
at Downsize.main(Downsize.java:9)
You must initialize the employees array. Once you read in the number of employees, do employees = new boolean[numEmp]; (after the line int numEmp = APIO.getInt();). Otherwise, it is null, so trying to access employees[i] throws a NullPointerException.
I see that you guys are beating around the bush in #mook's answer so let me just clarify so the OP can understand it well instead of guessing.
class Example {
int size;
boolean[] array;
void initArray() {
size = 5;
array = new boolean[size];
}
}
After declaring the size of the array and its type, you need to initialize the array. In the above example array holds 5 booleans.
If instead you write
class Example {
int size;
boolean[] array = new boolean[size];;
void initArray() {
size = 5;
}
}
Then since int is set to 0 by default, the size of array will be 0 even if you change the variable you used to declare the size later in the code. This will give you an error since you will iterate up to 5.
#mook's answer is correct.

How to implement a Multi Class Application

This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).

Boolean multidimensional arrays working with nested for loops - making it stop

I'm kind of stumped here.
I'm relatively new to Java/Programming in general. I want to make a program that "books seats" in a 4x4 grid. This multidimensional array will be of the type boolean so that if the seat is not taken, it returns false, but if it is taken it will return true. I want to be able to specify different seats, so like the first two rows will be a different section than the last two rows. Right now I have a method but it just books the entire first two rows as soon as I call that method (as it should, logically speaking). But I want to only be able to book one seat at a time, so that it will end that for loop as soon as one seat is booked. If I select that I want to book another seat, it will move to the next available seat in those rows or columns.
Here is the code so far:
import javax.swing.JOptionPane;
public class Seats{
int maxRows = 4;
int maxCols = 4;
boolean seating[][] = new boolean[maxRows][maxCols];
String bookSeat = null;
public static void main(String []args){
Seats seats = new Seats();
seats.start();
}
public void start(){
bookSeat = JOptionPane.showInputDialog(null, "Book a seat? (y/n)");
if(bookSeat.equals("y")){
bookSeat();
}else{
JOptionPane.showMessageDialog(null, "Okay.");
}
displaySeats(seating);
}
private boolean bookSeat(){
boolean isBooked = false;
for(int row = 0; row <2; row++){
for(int col = 0;col<maxCols;col++){
if (seating[row][col] == false){
seating[row][col] = true;
isBooked = true;
}
}
}
return isBooked;
}
private void displaySeats(boolean[][] anArray){
String seatTaken;
int r=0;
int c=0;
for(int display=0; display<1; display++){
for(r=0;r<anArray.length;r++){
for(c=0;c<anArray.length;c++){
if (seating[r][c]==false){
seatTaken = "O";
}
else{
seatTaken = "X";
}
System.out.print("\t[" + seatTaken + "] \t");
}
System.out.println("");
}
}
}
}
private boolean bookSeat(){
boolean isBooked = false;
for(int row = 0; row <2; row++){
for(int col = 0;col<maxCols;col++){
if (seating[row][col] == false){
seating[row][col] = true;
return true;
}
}
}
return false;
}
I think what you're looking to do is return once you find an open seat and book it -- as shown in the method above. This way the loops won't continue once you book a seat.
Assuming you mean that you want to exit this method as soon as it finds a seat.
private boolean bookSeat()
{
for(int row = 0; row <2; row++)
{
for(int col = 0;col<maxCols;col++)
{
if (seating[row][col] == false)
{
seating[row][col] = true;
return true;
}
}
}
return false;
}

Java hangman help, my code included

**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}
(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.
Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.
Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).
Classic java starter error. while check stetement should be
While(retry == true)

Categories

Resources