I am working on code for an assignment in which I have to make Wheel of Fortune, I am having trouble with building the string that will be shown to the user after each guess. I have the wheel spin working but I just can't seem to figure how to build the string. I can also answer any questions about this if you have any. Any help will be much appreciated. Here is my code so far:
class WheelOfFortune3 {
public static void main(String[] args) {
int result, location, newLocation, numGuess = 0;
String puzzle, guess;
String sub[] = new String[26];
for (int i = 0; i < sub.length; i++) {
sub[i] = "_";
}
result = wheelResult();
System.out.println("You spun $" + result);
puzzle = getPuzzle();
System.out.println(puzzle);
do {
guess = In.getString();
location = checkGuess(puzzle, guess);
if (location == -1) {
System.out.println("Incorrect guess");
}
if (location >= 0 && location <= 25) {
System.out.println("Correct guess");
newLocation = location + 1;
sub[numGuess] = puzzle.substring(location, newLocation);
for (int i = 0; i <= 10; i++) {
System.out.print(sub[i] + " ");
}
System.out.println("");
numGuess = numGuess + 1;
System.out.println(numGuess);
System.out.println(sub.length);
}
}
while (numGuess < sub.length);
}
public static int checkGuess(String puzzle, String guess) {
String word = puzzle;
int location;
location = word.indexOf(guess);
return location;
}
public static int wheelResult() {
int result;
int[] wheelSpin = new int[1];
wheelSpin[0] = (int)(24 * Math.random());
if (wheelSpin[0] == 1 || wheelSpin[0] == 18 || wheelSpin[0] == 22) {
result = 200;
return result;
} else if (wheelSpin[0] == 2 || wheelSpin[0] == 5) {
result = 900;
return result;
} else if (wheelSpin[0] == 0 || wheelSpin[0] == 3 || wheelSpin[0] == 15) {
result = 250;
return result;
} else if (wheelSpin[0] == 4 || wheelSpin[0] == 6 || wheelSpin[0] == 12 || wheelSpin[0] == 16) {
result = 300;
return result;
} else if (wheelSpin[0] == 7) {
result = 1500;
return result;
} else if (wheelSpin[0] == 9 || wheelSpin[0] == 11) {
result = 700;
return result;
} else if (wheelSpin[0] == 10 || wheelSpin[0] == 14 || wheelSpin[0] == 21) {
result = 500;
return result;
} else if (wheelSpin[0] == 13) {
result = 5000;
return result;
} else if (wheelSpin[0] == 23 || wheelSpin[0] == 19) {
result = 600;
return result;
} else if (wheelSpin[0] == 8 || wheelSpin[0] == 20) {
result = 100;
return result;
} else if (wheelSpin[0] == 17) {
result = 17;
return result;
}
return -1;
}
public static String getPuzzle() {
String puzzle;
//a long ride
return "A long ride";
//01234567890
}
}
This can be done using a List of Characters and the .contains() method like so:
List<Character> guessedCharacters = new ArrayList<>();
each time a player guesses a letter, add that letter to
the guessedCharacters List like this: guessedCharacters.add(char);
Then you can do something like this to generate the String to output to the player:
StringBuilder toShowSB = new StringBuilder();
for(int i=0,n=puzzle.length;i<n;i++){
if(guessedCharacters.contains(puzzle.charAt(i))){
toShowSB.append(puzzel.charAt(i));
}else{
toShowSB.append("_");
}
}
String toShow = toShowSB.toString();
This will create a String that holds all of the guessed letters in their places and an underscore denoting characters that have not been properly guessed yet.
I have been working on this problem for several hours now and I just cannot figure out what I am doing wrong here. Could anyone help point me in the right direction?
I was asked to write an Autocomplete program and I've completed everything except for this one method I cannot get working. Each term has: 1. String query and 2. long weight.
Here is the method:
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() { // LINE CAUSING PROBLEM
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) { // LINE CAUSING PROBLEM
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
My problem is that no matter how I mess with the method I always result in a NullPointerException(). Which, it points to this method (byReverseWeightOrder) as well as these two statements.
Arrays.sort(matches, Term.byReverseWeightOrder());
Term[] results = autocomplete.allMatches(prefix);
Here is the rest of the code if it can be found helpful:
Term
import java.util.Comparator;
public class Term implements Comparable<Term> {
public String query;
public long weight;
public Term(String query, long weight) {
if (query == null) {
throw new java.lang.NullPointerException("Query cannot be null");
}
if (weight < 0) {
throw new java.lang.IllegalArgumentException("Weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) {
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new java.lang.IllegalArgumentException("Cannot order with negative number of characters");
}
final int ref = r;
return
new Comparator<Term>() {
public int compare(Term t1, Term t2) {
String q1 = t1.query;
String q2 = t2.query;
int min;
if (q1.length() < q2.length()) {
min = q1.length();
}
else {
min = q2.length();
}
if (min >= ref) {
return q1.substring(0, ref).compareTo(q2.substring(0, ref));
}
else if (q1.substring(0, min).compareTo(q2.substring(0, min)) == 0) {
if (q1.length() == min) {
return -1;
}
else {
return 1;
}
}
else {
return q1.substring(0, min).compareTo(q2.substring(0, min));
}
}
};
}
public int compareTo(Term that) {
String q1 = this.query;
String q2 = that.query;
return q1.compareTo(q2);
}
public long getWeight() {
return this.weight;
}
public String toString() {
return this.weight + "\t" + this.query;
}
}
BinarySearchDeluxe
import java.lang.*;
import java.util.*;
import java.util.Comparator;
public class BinarySearchDeluxe {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) <= 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
return -1;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a == null || a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) < 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
return -1;
}
}
AutoComplete
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
public class Autocomplete {
public Term[] terms;
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException();
}
this.terms = terms.clone();
Arrays.sort(this.terms);
}
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int count = start;
System.out.println("Start: " + start + " End: " + end);
if (start == -1 || end == -1) {
// System.out.println("PREFIX: " + prefix);
throw new java.lang.NullPointerException();
} // Needed?
Term[] matches = new Term[end - start + 1];
//matches = Arrays.copyOfRange(terms, start, end);
for (int i = 0; i < end - start; i++) {
matches[i] = this.terms[count];
count++;
}
Arrays.sort(matches, Term.byReverseWeightOrder());
System.out.println("Finished allmatches");
return matches;
}
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
System.out.println("Finished numberMatches");
return end - start + 1; // +1 needed?
}
public static void main(String[] args) throws IOException {
// Read the terms from the file
Scanner in = new Scanner(new File("wiktionary.txt"));
int N = in.nextInt(); // Number of terms in file
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.nextLong(); // read the next weight
String query = in.nextLine(); // read the next query
terms[i] = new Term(query.replaceFirst("\t",""), weight); // construct the term
}
Scanner ip = new Scanner(System.in);
// TO DO: Data Validation Here
int k;
do {
System.out.println("Enter how many matching terms do you want to see:");
k = ip.nextInt();
} while (k < 1 || k > N);
Autocomplete autocomplete = new Autocomplete(terms);
// TO DO: Keep asking the user to enter the prefix and show results till user quits
boolean cont = true;
do {
// Read in queries from standard input and print out the top k matching terms
System.out.println("Enter the term you are searching for. Enter * to exit");
String prefix = ip.next();
if (prefix.equals("*")) {
cont = false;
break;
}
Term[] results = autocomplete.allMatches(prefix);
System.out.println(results.length);
for(int i = 0; i < Math.min(k,results.length); i++)
System.out.println(results[i].toString());
} while(cont);
System.out.println("Done!");
}
}
I apologize for the sloppy code, I have been pulling my hair out for awhile now and keep forgetting to clean it up.
Two examples:
Example 1:
int k = 2;
String prefix = "auto";
Enter how many matching terms do you want to see:
2
Enter the term you are searching for. Enter * to exit
auto
619695 automobile
424997 automatic
Example 2:
int k = 5;
String prefix = "the";
Enter how many matching terms do you want to see:
5
Enter the term you are searching for. Enter * to exit
the
5627187200 the
334039800 they
282026500 their
250991700 them
196120000 there
I have a simple class:
public class NPP {
// inputs
public int m__water_pressure = 0;
public boolean m__blockage_button = false;
public boolean m__reset_button = false;
public int old_m__pressure_mode = 0;
public boolean old_m__reset_button = false;
public boolean old_m__blockage_button = false;
public int old_m__water_pressure = 0;
// outputs
public int c__pressure_mode = 0;
public boolean c__the_overriden_mode = false;
public int c__the_safety_injection_mode = 0;
public int p__pressure_mode = 0;
public boolean p__the_overriden_mode = false;
public int p__the_safety_injection_mode = 0;
public void method__c__pressure_mode() {
if ( m__water_pressure >= 9 && old_m__water_pressure < 9 && c__pressure_mode == 0 ) {
p__pressure_mode = 1;
} else if ( m__water_pressure >= 10 && old_m__water_pressure < 10 && c__pressure_mode == 1 ) {
p__pressure_mode = 2;
} else if ( m__water_pressure < 9 && old_m__water_pressure >= 9 && c__pressure_mode == 1 ) {
p__pressure_mode = 0;
} else if ( m__water_pressure < 10 && old_m__water_pressure >= 10 && c__pressure_mode == 2 ) {
p__pressure_mode = 1;
}
}
public void method__c__the_overriden_mode() {
if ( m__blockage_button == true && old_m__blockage_button == false && m__reset_button == false && !(c__pressure_mode==2) ) {
p__the_overriden_mode = true;
} else if ( m__reset_button == true && old_m__reset_button == false && !(c__pressure_mode==2) ) {
p__the_overriden_mode = false;
} else if ( c__pressure_mode==2 && !(old_m__pressure_mode==2) ) {
p__the_overriden_mode = false;
} else if ( !(c__pressure_mode==2) && old_m__pressure_mode==2 ) {
p__the_overriden_mode = false;
}
}
public void method__c__the_safety_injection_mode() {
if ( c__pressure_mode == 0 && c__the_overriden_mode == true ) {
p__the_safety_injection_mode = 0;
} else if ( c__pressure_mode == 0 && c__the_overriden_mode == false ) {
p__the_safety_injection_mode = 1;
} else if ( c__pressure_mode == 1 || c__pressure_mode == 2 ) {
p__the_safety_injection_mode = 0;
}
}
}
And i've wrote this junit class:
import static org.junit.Assert.*;
import org.junit.Test;
public class NPPTest {
#Test
public void testMethod__c__pressure_mode() {
NPP npp = new NPP();
npp.m__water_pressure = 3;
npp.old_m__water_pressure = 5;
npp.c__pressure_mode = 2;
npp.method__c__pressure_mode();
assertEquals(1, npp.p__pressure_mode);
}
#Test
public void testMethod__c__the_overriden_mode() {
NPP npp = new NPP();
npp.m__blockage_button = false;
npp.old_m__blockage_button = true;
npp.m__reset_button = false;
npp.method__c__the_overriden_mode();
assertFalse(npp.p__the_overriden_mode);
}
#Test
public void testMethod__c__the_safety_injection_mode() {
NPP npp = new NPP();
npp.c__pressure_mode = 2;
npp.c__the_overriden_mode = false;
npp.method__c__the_safety_injection_mode();
assertEquals(1, npp.p__the_safety_injection_mode);
}
}
I've been asked to write some tests and to cover 100% of code coverage. But what exactly does it mean? How can i achieve this? I've ran Eclemma and i've got only 46%.
100% code coverage means that every line of code is covered by a test.
In other words, your test code should call and go through everything that has been written and make sure it works as expected.
In your case, it means that all the methods must be called and every if-else if case must be tested.
Even though 100% code coverage is very sexy, what matters most is the quality of your test suite.
85% code coverage might be near perfect if all the 15% left is some getters/setters, call to external APIs that is useless to check, glue code that is very very difficult to test and so on. It is up to you to realize what code can and should be tested and what code can be left without knowing that you are leaving holes (and bombs?) in your app.
I am continuing with my project for school and have seemed to encounter another error. So what is happening is basically I am receiving a null pointer exception even though the code looks fine. I believe something is wrong with my array, and even after hours of searching I can't seem to find the error. Once again, any help/solution would be greatly appreciated.
import java.util.*;
public class library {
private static students stu1 = new students(65435, "Bob", "Ted");
private static students stu2 = new students(45546, "Guy", "Sid");
private static students stu3 = new students(78688, "Tim", "Cas");
private static students stu4 = new students(45387, "Guy", "Jim");
private static students stu5 = new students(12367, "Dom", "Lam");
private static students stu6 = new students(45905, "Kid", "Loo");
private static students stu7 = new students(65484, "Mut", "Hum");
private static students stu8 = new students(34578, "Kim", "Hay");
private static students stu9 = new students(20457, "Roy", "Boy");
private static students stu0 = new students(15678, "Kil", "Bil");
private static students[] studentArray;
private static students[] stuArrayAlt;
private static boolean firstArrayStu = true;
// private static books bookName = new books("title",
// "author","category","isbn", cost, rating out of 10);
private static books book1 = new books(
"Harry Potter and the Deathly Hallows", "JK Rowling", "fantasy",
"9780739360385", 30.00, 9.0);
private static books book2 = new books("Angels and Demons", "Dan Brown",
"fiction", "9780828855495", 25.00, 8.5);
private static books book3 = new books("The Hunger Games",
"Suzanne Collins", "science fiction", "9780439023481", 20.00, 8.0);
private static books book4 = new books("A Game of Thrones",
"George R R Martin", "fantasy", "9780002245845", 54.50, 12.5);
private static books book5 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book6 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book7 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book8 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book9 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book0 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books[] bookArray;
private static books[] bookArrayAlt;
private static boolean firstArrayBook;
private static int year1;
private static int month1;
private static int date1;
public library() {
bookArray = new books[] { book1, book2, book3, book4, book5, book6,
book7, book8, book9, book0 };
firstArrayBook = true;
studentArray = new students[] { stu1, stu2, stu3, stu4, stu5, stu6,
stu7, stu8, stu9, stu0 };
firstArrayStu = true;
}
public static void main(String[] args) {
// System.out.println(stu1.getStuNum() + " " + stu1.getFirstName() +
// " "+ stu1.getLastName());
// books[] bookReturn = stu1.insertBook(book1);
// System.out.println(book1.getCheckInLibrary());
// System.out.println(book1.getCheckInLibrary());
// System.out.println(bookReturn[0].getName());
// books[] bookReturn2 = stu1.insertBook(book2);
// System.out.println(book2.getCheckInLibrary());
// System.out.println(book2.getCheckInLibrary());
// stu1.insertBook(book1);
// checkOutBook(stu1,book1);
// System.out.println(stu1);
// stu1=null;
// System.out.println(stu1);
/*
* stu1.lostBookFine(book1); System.out.println(stu1.getFineBalance());
* stu1.lostBookFine(book2); System.out.println(stu1.getFineBalance());
*/
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[(a.length) + 1];
System.arraycopy(a, 0, b, 0, a.length);
b[a.length] = 6;
// for(int i=0;i<b.length;i++)
// {
// System.out.println(b[i]);
// }
/*
* int[] c = new int[]{1,2,3,4,5,6}; b = new int[(c.length)+1];
*
* System.arraycopy( c, 0, b, 0, c.length ); b[c.length]=7;
*
* for(int i=0;i<b.length;i++) { System.out.println(b[i]); }
*/
// int[] date = enterDate();
// int[] date2 = book1.addTwoWeeks(date);
// int[]date2= book1.getDateDue();
System.out.println(studentArray[0].getFirstName());
//boolean array=checkStuNum(45456);
//System.out.println(array);
//students[]array=lookUpLastName("sid");
//array[0].getFirstName();
}
public static void returnBook(students borrower, books bookReturn) {
}
public static books[] lookUpTitleBooks(String title)// //////////////interchange
// the array-boolean
// firstArrayBook--two
// if statements
{
int counter = 0;
for (int i = 0; i < bookArray.length; i++) {
if (title.equalsIgnoreCase(bookArray[i].getTitle())
|| ((bookArray[i].getTitle().toLowerCase())).contains(title
.toLowerCase())) {
counter++;
}
}
books[] booksLookUp = new books[counter];
int counterS = 0;
for (int i = 0; i < bookArray.length; i++) {
if (title.equalsIgnoreCase(bookArray[i].getTitle())
|| ((bookArray[i].getTitle().toLowerCase())).contains(title
.toLowerCase())) {
booksLookUp[counterS] = bookArray[i];
counterS++;
}
}
return booksLookUp;
}
// look up last name of student
public static students[] lookUpLastName(String lName) {
students[] studentlName = new students[1] ;
if (firstArrayStu == true) {
int counter = 0;
System.out.println("check");
for (int i = 0; i < studentArray.length; i++) {
if (lName.equalsIgnoreCase(studentArray[i].getLastName()) || ((studentArray[i].getLastName()).contains(lName.toLowerCase())) ){
counter++;
System.out.println("check if");
}
System.out.println("check for");
}
studentlName = new students[counter];
int counterS = 0;
for (int i = 0; i < studentArray.length; i++) {
if (lName.equalsIgnoreCase(studentArray[i].getFirstName())
|| ((studentArray[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
studentlName[counterS] = studentArray[i];
counterS++;
}
}
}
if (firstArrayStu == false) {
int counter = 0;
for (int i = 0; i < stuArrayAlt.length; i++) {
if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName())
|| ((stuArrayAlt[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
counter++;
}
}
studentlName = new students[counter];
int counterS = 0;
for (int i = 0; i < stuArrayAlt.length; i++) {
if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName())
|| ((stuArrayAlt[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
studentlName[counterS] = stuArrayAlt[i];
counterS++;
}
}
}
return studentlName;
}
public static void checkOutBook(students borrower, books bookBorrow) {
boolean canBorrow1 = checkFine(borrower);
boolean canBorrow2 = checkBorrowedBooks(borrower);
boolean canBorrow3 = checkBorrowedBooks(bookBorrow);
if (canBorrow1 == false) {
System.out.println("Your fine is too damn high");// alert window and
// redirect to
// main menu-so
// he/she can
// pay it if he
// wants to
}
if (canBorrow2 == false) {
System.out.println("Your already have 3 books checked out");// alert
// window
// and
// redirect
// to
// main
// menu-
// so
// he/she
// can
// return
// a
// book
// if he
// wants
// to
}
if (canBorrow1 == false) {
System.out.println("This book has been checkd out");// alert window
// and redirect
// to main menu-
// so he/she can
// look for
// another book
// and check it
// out
}
if (canBorrow1 && canBorrow2 && canBorrow3) {
borrower.insertBook(bookBorrow);
bookBorrow.checkOutStatusChange();
// alert window to show successful check out and redirect to main
// menu
}
}
public static boolean checkFine(students borrower) {
boolean canBorrow1 = borrower.checkBorrowedBooks(borrower
.getBookArray());
return canBorrow1;
}
public static boolean checkBorrowedBooks(students borrower) {
boolean canBorrow2 = borrower.checkFine(borrower);
return canBorrow2;
}
public static boolean checkBorrowedBooks(books bookBorrow) {
boolean canBorrow3 = bookBorrow.getCheckInLibrary();
return canBorrow3;
}
public static int[] enterDate() {
Scanner input = new Scanner(System.in);
boolean dateTrue = false;
int year, month, date;
while (dateTrue == false) {
System.out.println("Enter year");
year = input.nextInt();
System.out.println("Enter month");
month = input.nextInt();
System.out.println("Enter date");
date = input.nextInt();
// checking first date----------------------------------------
year1 = ((year >= 2010) ? year : 0);
month1 = ((month >= 1 && month <= 12) ? month : 0);
if (month1 == 1) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 2 && (year1 % 4) != 0) {
date1 = ((date >= 1 && date <= 28) ? date : 0);
}
if (month1 == 2 && (year1 % 4) == 0) {
date1 = ((date >= 1 && date <= 29) ? date : 0);
}
if (month1 == 3) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 4) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 5) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 6) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 7) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 8) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 9) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 10) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 11) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 12) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 0 || date1 == 0 || year1 == 0) {
// do nothing boolean remains false
// put alert window here
} else {
dateTrue = true;
}
}
int[] dates = { year1, month1, date1 };
return dates;
}
public void createStudent(int stuNum, String fName, String lName) {
if (firstArrayStu == true) {
for (int i = 0; i < studentArray.length; i++) {
if (studentArray[i] == null) {
studentArray[i] = new students(stuNum, fName, lName);
} else if (i == (studentArray.length - 1)) {
stuArrayAlt = new students[studentArray.length + 1];
System.arraycopy(studentArray, 0, stuArrayAlt, 0,
studentArray.length);
stuArrayAlt[studentArray.length] = new students(stuNum,
fName, lName);
firstArrayStu = false;
}
}
} else if (firstArrayStu == false) {
for (int i = 0; i < stuArrayAlt.length; i++) {
if (stuArrayAlt[i] == null) {
stuArrayAlt[i] = new students(stuNum, fName, lName);
} else if (i == (stuArrayAlt.length - 1)) {
studentArray = new students[stuArrayAlt.length + 1];
System.arraycopy(stuArrayAlt, 0, stuArrayAlt, 0,
stuArrayAlt.length);
studentArray[stuArrayAlt.length] = new students(stuNum,
fName, lName);
firstArrayStu = true;
}
}
}
}
public static void createBook(String name, String author, String category,
String isbn, double cost, double sRating) {
if (firstArrayBook == true) {
for (int i = 0; i < bookArray.length; i++) {
if (bookArray[i] == null) {
bookArray[i] = new books(name, author, category, isbn,
cost, sRating);
} else if (i == (bookArray.length - 1)) {
bookArrayAlt = new books[bookArray.length + 1];
System.arraycopy(bookArray, 0, bookArrayAlt, 0,
bookArray.length + 1);
bookArrayAlt[bookArray.length] = new books(name, author,
category, isbn, cost, sRating);
firstArrayBook = false;
}
}
}
else if (firstArrayBook == false) {
for (int i = 0; i < bookArrayAlt.length; i++) {
if (bookArrayAlt[i] == null) {
bookArrayAlt[i] = new books(name, author, category, isbn,
cost, sRating);
} else if (i == (bookArrayAlt.length - 1)) {
bookArray = new books[bookArrayAlt.length + 1];
System.arraycopy(bookArrayAlt, 0, bookArray, 0,
bookArrayAlt.length + 1);
bookArray[bookArrayAlt.length] = new books(name, author,
category, isbn, cost, sRating);
firstArrayBook = false;
}
}
}
}
public static boolean deleteStudent(String lName, int stuNum) {
students[] arrayLookedUp = lookUpLastName(lName);
boolean deleted = false;
for (int i = 0; i < arrayLookedUp.length; i++) {
if ((arrayLookedUp[i].getStuNum()) == stuNum) {
System.out.println("checker");
if (firstArrayStu == true) {
for (int j = 0; j < studentArray.length; j++) {
if (arrayLookedUp[i] == studentArray[j]) {
studentArray[j] = null;
deleted = true;
break;
}
}
break;
} else if (firstArrayStu == false) {
for (int j = 0; j < stuArrayAlt.length; j++) {
if (arrayLookedUp[i] == stuArrayAlt[j]) {
stuArrayAlt[j] = null;
deleted = true;
break;
}
}
}
} else if (i == (arrayLookedUp.length - 1)) {
deleted = false;
}
}
return deleted;
}
public static boolean checkStuNum(int stuNum) {
// private static students[] studentArray;
// private static students[] stuArrayAlt;
// private static boolean firstArrayStu=true;
boolean stuNumNew = false;
System.out.println("test");
if (firstArrayStu == true) {
for (int i = 0; i < studentArray.length; i++) {
System.out.println("false");
if ((studentArray[i].getStuNum()) == stuNum) {
System.out.println("true");
stuNumNew = true;
break;
}
}
}
else if (firstArrayStu == false) {
for (int i = 0; i < stuArrayAlt.length; i++) {
if ((stuArrayAlt[i].getStuNum()) == stuNum) {
stuNumNew = true;
break;
}
}
}
return stuNumNew;
}
}
I have a student class with a constructor, and a method that states
public String getFirstName() {
return fName;
}
but still I am getting an error. I know it is a lot of code to go through, so once again any kind of help would be greatly appreciated.
As your code is currently written,
System.out.println(studentArray[0].getFirstName());
Will throw an NPE since you're never initializing the array.
private static students[] studentArray;
Just declares it, doesn't initialize it.
Maybe you should refactor your code as follows
private static ArrayList<students> studentArray = new ArrayList<students>();
// Inside the constructor or some method called before you access studentArray:
studentArray.add(stu1);
studentArray.add(stu2);
//...
// or, more concisely, since you're not using the temporary `students` variables:
studentArray.add(new students(65435, "Bob", "Ted"));
studentArray.add(new students(45546, "Guy", "Sid"));
//...
If you're committed to using an array and not a List,
private static students[] studentArray;
needs to be initialized with something like
private static students[] studentArray = new students[10];
and then you need to assign its elements
studentArray[0] = stu1;
or
studentArray[0] = new students(65435, "Bob", "Ted");
You should always create a object before trying to access it.
You have declared a reference pointing to a array :
private static students[] studentArray;
but never assigned any object to the reference. Hence you get a NullPointerException.
Use this :
private static students[] studentArray = new students[size];
Above code will create a new object (array of students), pointed by a reference variable (studentArray).
OR
You can use List or Set which are more efficient then array.
Well been working for hours today so i might be missing something silly, but, at this point I'm kinda blind with this and looking for an explanation for this behaviour
i made an example of the problem I'm having and the solution i found is not quite a solution.
The Problem: to the following function I pass 1 as shotCount and 9 as Countdown
the result when i debug, i see the first if run, and run the return 2, but then also the else decides to run to and finally return -1
public int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
BUT if i do this (same parameters) it works:
public int getNextShot(int shotCount, int Countdown)
{
int res = -2;
if ((shotCount == 1) && (Countdown != 10)) res = 2;
else if (shotCount == 0) res = 1;
else res = -1;
return res;
}
Am I missing something here?
Thanks :)
I think you are mistaken.
Sometimes the debugger in Eclipse acts like its jumping to the last line of the method call but then does return the correct value.
For example, I just copied and pasted your code and it ran fine for me. The below code prints 2.
public class AA {
public static void main(String[] args) {
System.out.println(getNextShot(1, 9));
}
public static int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
}
This code is OK. When I run this:
public static int getNextShot1(int shotCount, int Countdown) {
if ((shotCount == 1) && (Countdown != 10)) {
return 2;
} else if (shotCount == 0) {
return 1;
} else {
return -1;
}
}
public static int getNextShot2(int shotCount, int Countdown) {
int res = -2;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}
public static void main(String[] args) throws KeyStoreException, ParseException {
System.out.println(getNextShot1(1, 9));
System.out.println(getNextShot2(1, 9));
}
I get
2
2
on console :)
Second function could look like this (final keyword):
public static int getNextShot2(int shotCount, int Countdown) {
final int res;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}