Creating a circular queue with arrays in Java - java

The queue generates an error if more than 3 names are entered into it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at hotelobjects.Queue.addqueue(Queue.java:17)
at hotelobjects.HotelObjects.addCustomers(HotelObjects.java:82)
at hotelobjects.HotelObjects.main(HotelObjects.java:44)
Java Result: 1
How do I ensure that any names entered after the original 3 will be placed at the front of the queue - in a circular way.
package hotelobjects;
import java.util.*;
import java.io.*;
public class HotelObjects {
static Queue myQueue = new Queue();
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
String command;
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
for (int x = 0; x < myHotel.length; x++) {
myHotel[x] = new Room();
}
System.out.println("10 Rooms Created");
while (true) {
System.out.print("\nEnter command or 'X' to exit: ");
command = input.next();
command = command.toLowerCase();
if (command.charAt(0) == 'x') {
System.exit(0);
}
if (command.charAt(0) == 'a') {
addCustomers(myHotel);
}
if (command.charAt(0) == '3') {
displayNames(myHotel);
}
}
}
private static void addCustomers(Room myHotel[]) {
String roomName;
int roomNum;
System.out.println("Enter room number (0-10) or 11 to exit:");
Scanner input = new Scanner(System.in);
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
roomName = roomName.toLowerCase();
myHotel[roomNum].setName(roomName);
myQueue.addqueue(roomName);
}
else {
System.exit(0);
}
}
private static void displayNames(Room[] myHotel) {
System.out.println("The last 3 names entered are: ");
for (int x = 0; x < 3; x++) {
myQueue.takequeue();
}
}
}
Here is the 'queue' class:
package hotelobjects;
public class Queue {
String qitems[] = new String[3];
int front = 0, end = 0;
void addqueue(String roomName) {
qitems[end] = roomName;
end++;
}
void takequeue() {
if (end > front) {
System.out.println("Name Entered : " + qitems[front]);
front++;
} else {
System.out.println("No Name");
}
}
}

Increment your index module the maximum number of elements in the queue:
void addqueue(String roomName) {
qitems[end] = roomName;
end = (end + 1) % 3;
}
So you get:
end = (0 + 1) % 3 = 1
end = (1 + 1) % 3 = 2
end = (2 + 1) % 3 = 0
end = (0 + 1) % 3 = 1
...
You should also change the takequeue() method to consider the fact that the queue is now circular. Something like this:
void takequeue() {
System.out.println("Name Entered : " + qitems[front]);
front = (front + 1) % 3;
}
It is also a good idea to create a constant to store the queue capacity instead of repeating the 3 value all over the code:
private static final int CAPACITY = 3;

Related

How can I get my program back on track when printing out all student records?

import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.

How to give input array[] using scanner without space?

In this below program, I'm trying to check whether the number is ISBN or not. I'm giving input with spaces (eg: 0 3 0 6 4 0 6 1 5 2) because array only accepts it like this. I don't know how to give input without space to read. Can anyone help me how to read the number eg: 0306406152 and also it will read 10 numbers only like if(i==10) else it says it's not ISBN number to give output.
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
aa.digits = new int[10];
Scanner scan = new Scanner(System.in);
int i = 0;
while (scan.hasNextInt()) {
aa.digits[i] = scan.nextInt();
i++;
if (i == 10) // aa.CheckISBN();
{
break;
}
for (int j = 0; j < aa.digits.length; j++) {
// System.out.print(aa.digits[j]);
}
//System.out.println();
}
aa.CheckISBN();
}
}
SAMPLE OUTPUT: 0 3 0 6 4 0 6 1 5 2
it's valid ISBN number
When the number is given without spaces,
import java.io.*;
import java.util.*;
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
if(this.digits.length != 10)
{
System.out.println("sorry it's not valid ISBN");
return;
}
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
//System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
Scanner scan = new Scanner(System.in);
String num = scan.next(); //take input as a string
int[] digits = new int[num.length()];
for(int i = 0; i<digits.length; i++)
digits[i] = num.charAt(i) - '0';
aa.digits = digits;
aa.CheckISBN();
}
}
Or scan it as int to get number format validation for free:
public class ISBN {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
if (scan.hasNextInt()) {
checkISBN(scan.nextInt());
}
}
public static void checkISBN(int isbn) {
int sum = sum(digits(isbn));
int isbn1 = sum % 11;
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
private static int sum(int[] digits) {
return IntStream.rangeClosed(1, digits.length)
.map(i -> i * digits[digits.length - i])
.sum();
}
private static int[] digits(int isbn) {
return Integer.toString(isbn)
.chars()
.map(c -> c - '0')
.toArray();
}
}
N.B.: It works for ISBN both with or without leading zeros.

How to search an Array for a string

I am trying to create a hotel database program that has a search function whereby the user can type a name that is staying in the hotel and the program will display the room number for that person. The code below does recognize when the name entered is the same as an existing name in the program, however it also comes up with an error every time:
Exception in thread "main" java.lang.NullPointerException
at hotel.Hotel.findroom(Hotel.java:113)
at hotel.Hotel.main(Hotel.java:51)
Java Result: 1
I have also left question marks '???' in the code at the bottom as I have no idea how to get the program to display the room number of the matching name.
public class Hotel {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
String[] hotel = new String[12];
initialise(hotel);
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer(hotel);
}
if (command.charAt(0) == 'v') {
viewoccupants(hotel);
}
if (command.charAt(0) == 'e') {
emptyrooms(hotel);
}
if (command.charAt(0) == 'd') {
deleteroom(hotel);
}
if (command.charAt(0) == 'f') {
findroom(hotel);
}
}
}
private static void initialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++ ) hotelRef[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer(String[] hotel) {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom(String[] hotel) {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom(String[] hotel) {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
I got your problem. you need to declare the String[] hotel or String[] rooms as the global member. The scope of the String[] hotel would have been gone when the function execution is completed if you are using in another function or in main then it will be a different String array. So only you will be getting NPE. So your code should be like below,
public class Hotel {
/**
* #param args the command line arguments
*/
private static String[] hotel= new String[11];
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
initialise();
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer();
}
if (command.charAt(0) == 'v') {
viewoccupants();
}
if (command.charAt(0) == 'e') {
emptyrooms();
}
if (command.charAt(0) == 'd') {
deleteroom();
}
if (command.charAt(0) == 'f') {
findroom();
}
}
}
private static void initialise( ) {
for (int x = 0; x < 11; x++ ) hotel[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants() {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer() {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms() {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom() {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom() {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
Output:
initilise
Enter command : 1
Enter command : a
Enter room number (0-10) or 11 to stop:
1
Enter name for room 1 :
kalai
Enter command : f
Enter name:
kalai
kalai is located in room 1
Enter command :
you also could use lambda in java.
int i = 0;
hotel.asList().forEach(i++ -> s==roomName -> System.out.println(n " is located in room " + i));
You get a null pointer because you didn't initialize the last string inside hotel[]. Either you do that or you swap the object and parameter in function equals inside the loop in the findroom function. (roomname.equals(hotel[i])).
The problem originates because you created an array of 12 elements but then you always cicle index from 0 to 10, that is 11 elements, except in the find function where you cicle through the length of the array, that is 12 elements.
Always use "for(int i = 0; i < hotel.length; i++)" to cicle through your array.

Array not printing properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}

Java arraylist retrieving data min/max values

I am doing my Java homework for a class. I wrote the below store program that the user inputs a 4 digit id and what money they had for that store id. This information get's put in an array. totals and store id's are retrieved.
in the next part of my program I am to retrieve min and max values from each data group:even and odd store id numbers. I have tried to do this by retrieving the origonal data and putting them into a new array. even data into an even array and odd data into an odd array. in the following code I am testing the even part. Once it works I will replicate in the odd section.
Right now the following code skips my request. I don't know how to fix this.
Any insight would be greatly appreciated!
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Bonus
{
public static void main (String[] arg)
{
Scanner in = new Scanner(System.in);
String storeID, highID;
double grandTotalSales = 0;
double evenGrandTotal = 0;
double oddGrandTotal = 0;
double evenTotalSale;
double oddTotalSale;
double largestYet = 0;
double maxValue = 0;
int numPenn, numNick, numDime, numQuar, numHalf, numDol;
boolean more = true;
boolean report = true;
String input;
int inputopt;
char cont;
char check1, highStoreID;
Store myStore;
ArrayList<Store> storeList = new ArrayList<Store>();
ArrayList<Store> evenStoreList = new ArrayList<Store>();
while(more)
{
in = new Scanner(System.in);
System.out.println("Enter 4 digit store ID");
storeID = in.nextLine();
System.out.println("Enter num of Penny");
numPenn = in.nextInt();
System.out.println("Enter num of Nickel");
numNick = in.nextInt();
System.out.println("Enter num of Dime");
numDime = in.nextInt();
System.out.println("Enter num of Quarter");
numQuar = in.nextInt();
System.out.println("Enter num of Half dollars");
numHalf = in.nextInt();
System.out.println("Enter num of Dollar bills");
numDol = in.nextInt();
myStore = new Store(storeID, numPenn, numNick, numDime, numQuar, numHalf, numDol);
storeList.add(myStore);
in = new Scanner(System.in);
System.out.println("More stores: Yes or No");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'N')||(cont == 'n'))
more = false;
}
while(report)
{
in = new Scanner(System.in);
System.out.println("What would you like to do? \nEnter: \n1 print Odd Store ID's report \n2 print Even Store ID's report \n3 to Exit");
inputopt = in.nextInt();
if(inputopt == 2)
{
System.out.println("\nEven Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + "Even Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '0' || check1 == '2' || check1 == '4'|| check1 == '6' || check1 =='8')
{
myStore.findEvenValue();
evenTotalSale = myStore.getEvenValue();
evenGrandTotal = evenGrandTotal + Store.getEvenValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getEvenValue() + " | " + (storeList.get(i)).getEvenGrandValue());
}
}
in = new Scanner(System.in);
System.out.println("Do want to print the highest and lowest sales? \nEnter yes or no");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'Y')||(cont == 'y'))
{
evenTotalSale = 0;
for(int i = 1; i < evenStoreList.size(); ++i)
{
myStore = (Store)(evenStoreList.get(i));
highID = myStore.getStoreID();
myStore.findEvenValue();
largestYet = myStore.getEvenValue();
if(largestYet > evenTotalSale)
{
Collections.copy(storeList, evenStoreList);
System.out.println("Store ID with highest sales is: ");
System.out.println((evenStoreList.get(i)).getStoreID() + " | " + largestYet);
}
}
}
else if((cont == 'N')||(cont == 'n'))
report = true;
}
else
if(inputopt == 1)
{
System.out.println("\nOdd Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + " Odd Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '1' || check1 == '3' || check1 == '5'|| check1 == '7' || check1 =='9')
{
myStore.findOddValue();
oddTotalSale = myStore.getOddValue();
oddGrandTotal = oddGrandTotal + Store.getOddValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getOddValue() + " | " + (storeList.get(i)).getOddGrandValue());
}
}
}
else
if(inputopt == 3)
report = false;
} // close while report
}// close of main
} // close class
class store:
public class Store
{
private String storeID;
private int numPenn, numNick, numDime, numQuar, numHalf, numDol;
Coin penn = new Coin("Penn", 0.01);
Coin nick = new Coin("Nickel", 0.05);
Coin dime = new Coin("Dime", 0.10);
Coin quar = new Coin("Quar", 0.25);
Coin half = new Coin("Half", 0.50);
Coin dol = new Coin("Dollar", 1.00);
private static double evenTotalSale;
private static double oddTotalSale;
static double evenGrandTotal = 0;
static double oddGrandTotal = 0;
public Store (String storeID, int numPenn, int numNick, int numDime, int numQuar, int numHalf, int numDol)
{
this.storeID = storeID;
this.numPenn = numPenn;
this.numNick = numNick;
this.numDime = numDime;
this.numQuar = numQuar;
this.numHalf = numHalf;
this.numDol = numDol;
}
public void findEvenValue()
{ evenTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
evenGrandTotal = evenGrandTotal + evenTotalSale;
}
public static double getEvenValue()
{
return evenTotalSale;
}
public void findOddValue()
{ oddTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
oddGrandTotal = oddGrandTotal + oddTotalSale;
}
public static double getOddValue()
{
return oddTotalSale;
}
public static double getOddGrandValue()
{
return oddGrandTotal;
}
public static double getEvenGrandValue()
{
return evenGrandTotal;
}
public String getStoreID()
{
return storeID;
}
}
your evenStoreList is empty.

Categories

Resources