Array null pointer exception error - java
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.
Related
UVa 162 - Beggar My Neighbour
The logic is very simple, but I don't know why my code is getting WA. If you can point out something wrong with the logic, please help. Problem: https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=98&mosmsg=Submission+received+with+ID+20986582 Source: import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; public class UVa_00162 { static Map<Character, Integer> faceCards = new HashMap<Character, Integer>(); static { faceCards.put('A', 4); faceCards.put('K', 3); faceCards.put('Q', 2); faceCards.put('J', 1); } static Stack<String> dealerHand = new Stack<>(); static Stack<String> nonDealerHand = new Stack<>(); static Stack<String> table = new Stack<>(); static enum GameStatus { CONTINUE, DEALER_WIN, NONDEALER_WIN }; static GameStatus status = GameStatus.CONTINUE; static void play() { String curCard; boolean nonDealerTurn = true; int penalty; char key; while (true) { if (nonDealerHand.size() == 0) { status = GameStatus.DEALER_WIN; break; } if (dealerHand.size() == 0) { status = GameStatus.NONDEALER_WIN; break; } curCard = nonDealerTurn ? nonDealerHand.pop() : dealerHand.pop(); table.push(curCard); nonDealerTurn = !nonDealerTurn; key = curCard.charAt(1); if (faceCards.containsKey(key)) { penalty = faceCards.get(key); while (penalty > 0) { if (nonDealerHand.size() == 0 || dealerHand.size() == 0) break; curCard = nonDealerTurn ? nonDealerHand.pop() : dealerHand.pop(); --penalty; table.push(curCard); key = curCard.charAt(1); if (faceCards.containsKey(key)) { penalty = faceCards.get(key); nonDealerTurn = !nonDealerTurn; } } if (nonDealerHand.size() == 0) { status = GameStatus.DEALER_WIN; break; } if (dealerHand.size() == 0) { status = GameStatus.NONDEALER_WIN; break; } // place the heap face down under current hand if (nonDealerTurn) { while (!table.isEmpty()) dealerHand.insertElementAt(table.remove(0), 0); nonDealerTurn = false; } else { while (!table.isEmpty()) nonDealerHand.insertElementAt(table.remove(0), 0); nonDealerTurn = true; } } } } #SuppressWarnings("resource") public static void main(String[] args) { Scanner input = new Scanner(System.in); String s; while(true) { s = input.next(); if (s.equals("#")) break; nonDealerHand.push(s); dealerHand.push(input.next()); int count = 3; while (count <= 52) { nonDealerHand.push(input.next()); ++count; dealerHand.push(input.next()); ++count; } play(); if (status==GameStatus.DEALER_WIN) System.out.println("1 " + dealerHand.size()); else System.out.println("2 " + nonDealerHand.size()); nonDealerHand.clear(); dealerHand.clear(); table.clear(); status = GameStatus.CONTINUE; } } }
5 Card Poker Hand JAVA-Analyze and Categorize
Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent. Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card. I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind. Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind. Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4. Any suggestions to my code? public static void main(String[] args) { Scanner input = new Scanner(System.in); final int HAND_SIZE = 5; int[] hand = new int[HAND_SIZE]; getHand(hand); //Prompt user for hand sortHand(hand);//Sort hand in ascending order if(containsFullHouse(hand)) { System.out.print("FULL HOUSE!"); } else if(containsStraight(hand)) { System.out.print("STRAIGHT!"); } else if(containsFourOfAKind(hand)) { System.out.print("FOUR OF A KIND!"); } else if(containsThreeOfAKind(hand)) { System.out.println("THREE OF A KIND!"); } else if(containsTwoPair(hand)) { System.out.println("TWO PAIRS!"); } else if(containsPair(hand)) { System.out.println("PAIR!"); } else System.out.println("High Card!"); } public static void getHand(int[] hand) { Scanner input = new Scanner(System.in); System.out.println("Enter five numeric cards, 2-9, no face cards please"); for(int index = 0; index < hand.length; index++) { System.out.print("Card " + (index + 1) + ": "); hand[index] = input.nextInt(); } } public static void sortHand(int[] hand) { int startScan, index, minIndex, minValue; for(startScan = 0; startScan < (hand.length-1); startScan++) { minIndex = startScan; minValue = hand[startScan]; for(index = startScan + 1; index <hand.length; index++) { if(hand[index] < minValue) { minValue = hand[index]; minIndex = index; } } hand[minIndex] = hand[startScan]; hand[startScan] = minValue; } } public static boolean containsPair(int hand[]) { boolean pairFound = false; int pairCount = 0; int startCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startCheck) == 0) { pairCount++; } startCheck = hand[index]; } if (pairCount == 1) { pairFound = true; } else if(pairCount !=1) { pairFound = false; } return pairFound; } public static boolean containsTwoPair(int hand[]) { boolean twoPairFound = false; int twoPairCount = 0; int startCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startCheck) == 0) { twoPairCount++; } startCheck = hand[index]; } if (twoPairCount == 2) { twoPairFound = true; } else if(twoPairCount != 2) { twoPairFound = false; } return twoPairFound; } public static boolean containsThreeOfAKind(int hand[]) { boolean threeFound = false; int threeKind = 0; int startCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startCheck) == 0) { threeKind++; } startCheck = hand[index]; } if(threeKind == 3) { threeFound = true; } else if(threeKind !=3) { threeFound = false; } return threeFound; } public static boolean containsStraight(int hand[]) { boolean straightFound = false; int straight = 0; int startCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startCheck) == 1) { straight++; } startCheck = hand[index]; } if(straight == 4) { straightFound = true; } return straightFound; } public static boolean containsFullHouse(int hand[]) { boolean fullHouseFound = false; int pairCheck = 0; int startPairCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startPairCheck) == 0) { pairCheck++; } startPairCheck = hand[index]; } int threeOfKindCheck = 0; int startThreeKindCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startThreeKindCheck) == 0) { threeOfKindCheck++; } startThreeKindCheck = hand[index]; } if(pairCheck == 1 && startThreeKindCheck == 3) { fullHouseFound = true; } return fullHouseFound; } public static boolean containsFourOfAKind(int hand[]) { boolean fourFound = false; int fourKind = 0; int startCheck = hand[0]; for(int index = 1; index < hand.length; index++) { if((hand[index] - startCheck) == 0) { fourKind++; } startCheck = hand[index]; } if(fourKind == 1) { fourFound = true; } else if(fourKind !=4) { fourFound = false; } return fourFound; } }
Some hints. Start with the highest hand. This eliminates lots of logic. I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind. But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.
How can I check java console output
I am making SOS game with "stack".No other data structures such as normal array, string etc. Gameboard size 3*6 and I am using random for determining letters. But I don't know is the game over or not. How can I control is there any horizontal or vertical sos at the console Here is my code(I am beginner) public static void main(String[] args) { Random rnd = new Random(); Stack S1 = new Stack(6); Stack S2 = new Stack(6); Stack S3 = new Stack(6); Stack ts1 = new Stack(6); Stack ts2 = new Stack(6); Stack ts3 = new Stack(6); int Round = 0; int satir; boolean winner = false; // for S1 int i = 0; while (i != 6) { // 6time i++; // System.out.println(i); if (rnd.nextBoolean()) { S1.push("S"); } else { S1.push("O"); } } // for S2 i = 0; while (i != 6) { i++; if (rnd.nextBoolean()) { S2.push("S"); } else { S2.push("O"); } } // for S3 i = 0; while (i != 6) { i++; if (rnd.nextBoolean()) { S3.push("S"); } else { S3.push("O"); } } int a = 0, b = 0, c = 0; int tempa = a; int tempb = b; int tempc = c; while (!winner) { System.out.println("User" + ((Round % 2) + 1) + ":"); // User1: // User2: satir = rnd.nextInt(3) + 1; if (satir == 1 && a != 6) { a++; } if (satir == 2 && b != 6) { b++; } if (satir == 3 && c != 6) { c++; } tempa = a; tempb = b; tempc = c; System.out.print("S1 "); while (a > 0) { // S1 in icini yazdir bosalt ts1e kaydet System.out.print(S1.peek() + " "); ts1.push(S1.pop()); a--; } a = tempa; while (!ts1.isEmpty()) { // S1i tekrar doldur S1.push(ts1.pop()); } System.out.println(); System.out.print("S2 "); while (b > 0) { // S2 in icini yazdir bosalt ts1e kaydet System.out.print(S2.peek() + " "); ts2.push(S2.pop()); b--; } b = tempb; while (!ts2.isEmpty()) { // S2i tekrar doldur S2.push(ts2.pop()); } System.out.println(); System.out.print("S3 "); while (c > 0) { // S3 in icini yazdir bosalt ts1e kaydet System.out.print(S3.peek() + " "); ts3.push(S3.pop()); c--; } c = tempc; while (!ts3.isEmpty()) { // S3i tekrar doldur S3.push(ts3.pop()); } System.out.println(); // check if there is sos winner=true; if (a > 2) { //check S1 Horizontal for (int yatay1 = 0; yatay1 < a; yatay1++) { if (S1.peek().equals("S")) { ts1.push(S1.pop()); if (S1.peek().equals("O")) { ts1.push(S1.pop()); if (S1.peek().equals("S")) { System.out.println("SOS-wow"); winner = true; } else { while (!ts1.isEmpty()) { S1.push(ts1.pop()); } } } else { S1.push(ts1.pop()); } } } } Round++; } // end of loop }
Time limit exceeded online judge
This is the problem : Input The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T lines contains a positive integer N that is no more than 80 digits in length. Output The output of each test case will be a single line containing the smallest palindrome that is greater than or equal to the input number. Sample Input 2 42 321 Sample Output 44 323 I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit) class Main { static String ReadLn (int maxLg) { byte lin[] = new byte [maxLg]; int lg = 0, car = -1; String line = ""; try { while (lg < maxLg) { car = System.in.read(); if ((car < 0) || (car == '\n')) break; lin [lg++] += car; } } catch (IOException e) { return (null); } if ((car < 0) && (lg == 0)) return (null); // eof return (new String (lin, 0, lg)); } static boolean isPalandriome(String s){ String newString = ""; for(int i =s.length()-1;i >= 0; i--){ newString += s.charAt(i); } if(newString.equals(s)) return true; else return false; } public static void main(String[] args) { BigInteger entredNumber; String input; input = Main.ReadLn(10); int tests = Integer.parseInt(input); List<BigInteger> numbers = new ArrayList<BigInteger>(); for (int i =0;i<tests;i++) { input = Main.ReadLn(100); entredNumber = new BigInteger(input); numbers.add(entredNumber); } for(int i=0;i<tests;i++){ BigInteger number = numbers.get(i); while(!isPalandriome(String.valueOf(number))){ number = number.add(BigInteger.ONE); } System.out.println(number); } } } I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { CustomReader cr = new CustomReader(1000000); int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex; StringBuilder output = new StringBuilder(); byte[] input; boolean isAppend1 = false; for (int i = 0; i < T; i++) { input = cr.nextInput(); fStartIndex = bStartIndex = cr.getCurrInputLength() / 2; isAppend1 = false; if (cr.getCurrInputLength() % 2 == 0) { bStartIndex--; } fIndex = fStartIndex; bIndex = bStartIndex; while (input[bIndex] == input[fIndex]) { if (bIndex - 1 < 0) { break; } else { bIndex--; fIndex++; } } if (input[bIndex] > input[fIndex]) { while (bIndex >= 0) { input[fIndex++] = input[bIndex--]; } } else { if (input[bStartIndex] < 57) { input[bStartIndex] = (byte) (input[bStartIndex] + 1); } else { bIndex = bStartIndex; while (bIndex >= 0 && input[bIndex] == 57) { input[bIndex] = 48; bIndex--; } if (bIndex >= 0) { input[bIndex] = (byte) (input[bIndex] + 1); } else { input[0] = 49; if (fStartIndex != bStartIndex) { input[fStartIndex] = 48; bStartIndex = fStartIndex; } else { input[fStartIndex + 1] = 48; bStartIndex = fStartIndex = fStartIndex + 1; } isAppend1 = true; } } while (bStartIndex > -1) { input[fStartIndex++] = input[bStartIndex--]; } } for (int j = 0; j < cr.getCurrInputLength(); j++) { output.append((char) input[j]); } if (isAppend1) { output.append("1"); } output.append("\n"); } System.out.print(output.toString()); // genInput(); } private static class CustomReader { private byte[] buffer; private byte[] currInput = new byte[1000000]; private int currInputLength; private int currIndex; private int validBytesInBuffer; CustomReader(int buffSize) { buffer = new byte[buffSize]; } public int nextInt() throws IOException { int value; byte b; while (true) { b = getNextByte(); if (b > 47 && b < 58) { break; } } value = b - 48; while (true) { b = getNextByte(); if (b > 47 && b < 58) { value = (value * 10) + (b - 48); } else { break; } } return value; } public byte[] nextInput() throws IOException { byte b; this.currInputLength = 0; while (true) { b = getNextByte(); if (b > 47 && b < 58) { break; } } currInput[currInputLength++] = b; while (true) { b = getNextByte(); if (b > 47 && b < 58) { currInput[currInputLength++] = b; } else { break; } } return this.currInput; } public int getCurrInputLength() { return this.currInputLength; } private byte getNextByte() throws IOException { if (currIndex == buffer.length || currIndex == validBytesInBuffer) { validBytesInBuffer = System.in.read(buffer); currIndex = 0; } return buffer[currIndex++]; } } public static void genInput() { for (int i = 0; i < 100; i++) { System.out.println((int) (Math.random() * 1000000000)); } } }
IndexOutOfBoundsException problems
I hope someone can help me with an IndexOutOfBoundsException error. I can set the amount of units within a territory, and I can set the owner of the territory however the defend function is causing a problem. Trace: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.RangeCheck(ArrayList.java:547) at java.util.ArrayList.get(ArrayList.java:322) at stackOverflow.Territory.calculateLoses(Territory.java:136) at stackOverflow.Territory.defend(Territory.java:95) at stackOverflow.Territory.defend(Territory.java:40) at stackOverflow.Territory.main(Territory.java:155) import java.util.ArrayList; import java.util.Collections; import java.util.List; public enum Territory { // Europe GREATBRITAIN("Great Britain"), ICELAND("Iceland"); private final String name; private int numberOfUnits; private Player player; private int ad = 0, dd = 0; private Territory(String name) { this.name = name; this.numberOfUnits = 0; this.player = null; } public void setOwner(Player p) { this.player = p; } public Player getOwner() { return this.player; } public int getNumberUnits() { return this.numberOfUnits; } public void setNumberUnits(int units) { this.numberOfUnits = units; } public boolean defend(Territory attacker) throws Exception { return defend(attacker, attacker.numberOfUnits - 1); } public boolean defend(Territory attacker, int attackingUnits) throws Exception { if (attackingUnits > (attacker.getNumberUnits() - 1)) { throw new Exception("Invalid number of units"); } attacker.setNumberUnits(attacker.numberOfUnits - attackingUnits); Player defender = this.player; this.player = null; int defendingUnits = this.numberOfUnits; this.numberOfUnits = 0; if (this.numberOfUnits >= 3 && defendingUnits >= 2) { ad = 3; dd = 2; } if (this.numberOfUnits >= 3 && defendingUnits == 1) { ad = 3; dd = 1; } if (this.numberOfUnits == 2 && defendingUnits >= 2) { ad = 2; dd = 2; } if (this.numberOfUnits == 2 && defendingUnits == 1) { ad = 2; dd = 1; } if (this.numberOfUnits == 1 && defendingUnits >= 2) { ad = 1; dd = 2; } if (this.numberOfUnits == 1 && defendingUnits == 1) { ad = 1; dd = 1; } if (this.name == "Great Britan" || this.name == "Central America" || this.name == "Argentina" || this.name == "Egypt" || this.name == "Western Australia" || this.name == "India") { dd++; } List<Die> attackerDice = createDice(ad); List<Die> defenderDice = createDice(dd); System.out.printf("Attacker: %d \tDefender: %d\n", attackingUnits, defendingUnits); while (attackingUnits > 0 && defendingUnits > 0) { roll(attackerDice); System.out.println(attackerDice); roll(defenderDice); System.out.println(defenderDice); attackingUnits -= calculateLoses(attackerDice, defenderDice, false); defendingUnits -= calculateLoses(defenderDice, attackerDice, true); System.out.printf("Attacker: %d \tDefender: %d\n", attackingUnits, defendingUnits); } if (defendingUnits > 0) { this.player = defender; this.numberOfUnits = defendingUnits; return true; } else if (attackingUnits > 0) { this.numberOfUnits = attackingUnits; this.player = attacker.player; return false; } else { // No one owns the territory as all units died return false; } } private List<Die> createDice(int number) { List<Die> dice = new ArrayList<Die>(); for (int i = 0; i < number; i++) { dice.add(new Die()); } roll(dice); return dice; } private void roll(List<Die> dice) { for (Die d : dice) { d.roll(); } Collections.sort(dice); } private int calculateLoses(List<Die> diceOne, List<Die> diceTwo, boolean defender) { int number = 0; for (int i = 0; i < 2; i++) { int comparison = diceOne.get(i).compareTo(diceTwo.get(i)); if (comparison > 0 || (!defender && comparison == 0)) { number++; } } return number; } String units() { return "" + numberOfUnits; } public static void main(String[] args) throws Exception { Territory.GREATBRITAIN.setNumberUnits(5); System.out.println(Territory.GREATBRITAIN.getNumberUnits()); Territory.ICELAND.setNumberUnits(5); System.out.println(Territory.ICELAND.getNumberUnits()); Territory.GREATBRITAIN.defend(Territory.ICELAND); } }
It looks like either ad or dd or both are 0. That makes sense, given this code: this.numberOfUnits = 0; // Lots of these, all requiring numberOfUnits to be greater than 0 if (this.numberOfUnits >= 3 && ...) { ad = ...; dd = ...; } How do you ever expect to get into any of those if blocks, when you've just set numberOfUnits to 0? This is only one of the problems in your code. Others have pointed out other aspects of either style or correctness. I'm not going to try to fix all of your code here - but you should analyze how you could have diagnosed this yourself. Did you try stepping through the code in a debugger, for example?
This code is wrong: if (this.name == "Great Britan" || this.name == "Central America" || this.name == "Argentina" || this.name == "Egypt" || this.name == "Western Australia" || this.name == "India") { dd++; } Use this.name.equals("Great Britain") to test if strings contain the same characters, rather than whether they are stored at the same location in memory. Also, your many separate if statements look like bad practice; use else or something to check you hit at least one case - you clearly don't hit any of the this.numberOfUnits >= [stuff] cases after setting this.numberOfUnits = 0;.