Method input showing unexpected output [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 10 months ago.
I have a method called processClaims() which takes input from the user "by asking how many files need to be claimed". The method is shown below.
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
The problem is with the array or the for loop I belive. The output is shown below which isn't correct
[LInsuranceSystem$EarthquakeInsurance;#548c4f57
If that is wrong here is the whole code, I am having trouble debugging this.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class Slack
{
public static void main(String[] args) throws FileNotFoundException {
InsuranceSystem insuranceSystem = new InsuranceSystem();
insuranceSystem.start();
}
}
class InsuranceSystem {
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
ArrayList<String> claimsReport = new ArrayList<>();
EarthquakeInsurance[] claims;
String fileName = " ";
char cont = ' ', correct = ' ';
public InsuranceSystem() {
}
public void start() throws FileNotFoundException {
System.out.println("MUTUALLY ACCIDENTAL INC.");
System.out.println("Do you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N': ");
cont = input.next().charAt(0); //reads user input from input and applies to it var cont
input.nextLine(); //clears buffer
if (cont == 'y' || cont == 'Y') {
processClaims();
writeClaimsRecords();
checkInputFile();
}
printThankYou();
}
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
public void writeClaimsRecords() throws FileNotFoundException
{
String record = " ";
Scanner input = new Scanner(System.in);
System.out.println("Enter the file name for the claims' records (WARNING: This will erase a pre-existing file!): ");
fileName = input.nextLine();
PrintWriter outputFile = new PrintWriter(fileName);
for(int i = 0; i < claims.length; i++){
record = String.format("%s, %f, %f%n", claims[i].insured, claims[i].homeInsVal, claims[i].richter);
}
outputFile.printf(record);
outputFile.close();
System.out.println("Data written to the" + fileName + " file.");
}
public void checkInputFile() throws FileNotFoundException {
String fileRecord = " ";
File file = new File("Claims.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
fileRecord = inputFile.nextLine();
System.out.println(fileRecord);
System.out.println("");
inputFile.close();
}
}
public void printThankYou() {
System.out.println("Thank you for using the Earthquake Coverage Analyzer.");
}
class EarthquakeInsurance {
//STUDENTS INSERT LINE COMMENTS DESCRIPTIVE OF THE PURPOSE OF EACH VARIABLE.
private String insured;
private String coverage;
private String message;
private double homeInsVal;
private double richter;
private double payout;
private double deductible;
private Scanner input = new Scanner(System.in);
private boolean repeat;
private char correct;
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance() {
}//END Default Constructor
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance(String insured, double homeInsVal, double richter) {
setInsured(insured);
setHomeInsVal(homeInsVal);
setRichter(richter);
}//END EarthquakeInsurance(String, double, double)
/**
* STUDENTS CODE copy() AND PROVIDE METHOD BOX COMMENTS.
*/
public String copy() {
String insuranceObj = " ";
return insuranceObj;
}
/**
* STUDENTS CODE equals AND PROVIDE METHOD BOX COMMENTS.
*/
public boolean equals(String aClaim) {
boolean isEqual = false;
if (isEqual = false) {
isEqual = true;
}
return isEqual;
}
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setInsured(String insured) {
this.insured = insured;
}//END setInsured(String): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setHomeInsVal(double homeInsVal) {
this.homeInsVal = homeInsVal;
}//END setHomeInsVal(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setRichter(double richter) {
this.richter = richter;
}//END setRichter(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setInsured() {
String insuredCopy = null, first = null, last = null;
int indexOfSpace = 0;
do {
System.out.printf("%nMUTUALLY ACCIDENTAL, INC."
+ "%nEarthquake Coverage Analyzer"
+ "%n%nPlease enter your name: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
while (!isAlpha(insuredCopy)) {
System.out.printf("%nInvalid name! Please re-enter: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
}//while insured's name is NOT alphabetic
System.out.printf("%nYour Name: %s"
+ "%n%nIs this name correct? \'Y\' or \'N\': ",
insured);
correct = input.nextLine().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
} while (repeat); //do-while insured name is not correct
indexOfSpace = insured.indexOf(" "); //Locate where the space is in insured.
if (indexOfSpace > 0) {
first = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, indexOfSpace).toLowerCase();
last = Character.toUpperCase(insured.charAt(indexOfSpace + 1))
+ insured.substring(indexOfSpace + 2, insured.length()).toLowerCase();
insured = first + " " + last;
}//if there is more than one name, capitalize the first letter in each
else {
insured = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, insured.length()).toLowerCase();
}//else capitalize first letter of a single name
}//END setInsured(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setHomeInsVal() {
do {
do {
System.out.printf("%nPlease enter the insured value of your home: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when homeInsVal is invalid
homeInsVal = input.nextDouble();
if (homeInsVal < 0) {
System.out.printf("%nThe insured value of your home cannot be less than or equal to 0.%n");
repeat = true;
}//END if homeInsVal less than zero then prompt again
else {
System.out.printf("%nHome\'s Insured Value: $%,.0f"
+ "%n%nIs this insured value correct? \'Y\' or \'N\': ",
homeInsVal);
correct = input.next().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of insured value
} while (repeat); //END do-while repeats when homeInsVal is not correct
}//END setHomeInsVal(): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setRichter() {
do {
do {
System.out.printf("%nRichter Scale Damage Assessment"
+ "%n 9.0+ Total destruction."
+ "%n 8.0 Most structures fell."
+ "%n 7.0 Many buildings destroyed."
+ "%n 6.0 Many buildings considerably damaged, some collapsed."
+ "%n 4.5 Damage to poorly constructed buildings."
+ "%n 3.5 Felt by many people, no destruction."
+ "%n 0 Generally not felt by people."
+ "%n%nPlease enter the Richter scale value for the earthquake: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when richter is invalid
richter = input.nextDouble();
if (richter < 0) {
System.out.printf("%nInvalid! Richter cannot be negative. Please re-enter.%n");
repeat = true;
}//END if richter less than zero then prompt again
else {
System.out.printf("%nRichter Scale: %.2f"
+ "%n%nIs this richter value correct? \'Y\' or \'N\': ",
richter);
correct = input.next().toLowerCase().charAt(0);
input.nextLine();
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of richter
} while (repeat); //END do-while repeats when homeInsVal is not correct
testRichter();
}//END setRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
private void testRichter() {
if (richter >= 9.0) {
payout = homeInsVal * .90;
deductible = homeInsVal * .10;
message = "Total destruction.";
}//END if richter >= 9.0 else richter < 9.0
else if (richter >= 8.0) {
payout = homeInsVal * .80;
deductible = homeInsVal * .20;
message = "Most structures fell.";
}//END if richter >= 8.0 else richter < 8.0
else if (richter >= 7.0) {
payout = homeInsVal * .70;
deductible = homeInsVal * .30;
message = "Many buildings destroyed.";
}//END if richter >= 7.0 else richter < 7.0
else if (richter >= 6.0) {
payout = homeInsVal * .60;
deductible = homeInsVal * .40;
message = "Many buildings considerably damaged, some collapsed.";
}//END if richter >= 6.0 else richter < 6.0
else if (richter >= 4.5) {
payout = homeInsVal * .50;
deductible = homeInsVal * .50;
message = "Damage to poorly constructed buildings.";
}//END if richter >= 4.5 else richter < 4.5
else if (richter >= 3.5) {
payout = 0;
deductible = 0;
message = "Felt by many people, no destruction.";
}//END if richter >= 3.5 else richter < 3.5
else if (richter >= 0) {
payout = 0;
deductible = 0;
message = "Generally not felt by people.";
}//END if richter >= 0 else richter < 0
}//END testRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getInsured() {
return insured;
}//END getInsured(): int
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getHomeInsVal() {
return homeInsVal;
}//END getHomeInsVal(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getRichter() {
return richter;
}//END getRichter(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getPayout() {
return payout;
}//END getPayout(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getDeductible() {
return deductible;
}//END getDeductible(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getMessage() {
return message;
}//END getMessage(): String
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void validateNumber() {
if (repeat) //AS LONG AS THE INPUT IS "NOT" AN INTEGER OR DOUBLE
{
input.next(); //CONSUME NON-NUMERIC VALUE.
System.out.printf("%nWarning: You entered an invalid integer or "
+ "floating-point value.%n"); //RE-PROMPT
}//END if repeat when a number is an invalid type
}//END validateNumber(boolean): void
/**
* chars() returns the integer values of the characters in word.
* <p>
* allMatch determines whether the integer values for each character
* matches the predicate (criterion) that each character is a letter.
* <p>
* The :: is a method reference operator for calling isLetter from
* the Character class.
*
* #param word is the incoming String value to test.
* #return is true when the word is not empty and is alphabetic
* or false when it isn't.
*/
public final boolean isAlpha(String word) {
/* Test to see if the word is not empty AND if each letter
* in a word is an alphabetic character.
*/
return word != null && word.chars().allMatch(Character::isLetter);
}//END isAlpha(String): final boolean
}//END CLASS EarthquakeInsurance
}

Mistake 1)
for ( EarthquakeInsurance eachClaim : claims);
remove semi
Mistake 2)
System.out.println(claims);
Yes you are print the whole list
See also How do I print my Java object without getting "SomeType#2f92e0f4"?

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.

java.lang.StringOutOfBoundsException can't figure it out

This code is supposed to get check whether a number is a palindrome.
Whenever I run the method check Palindrome its comes up with a java.lang.StringOutOfBoundsException.
Please help.
import java.util.*;
/**
* Lab 1 .
* #author Kevin Rasquinha
* #version 30 July 2016
*/
public class Lab1
{
private Scanner scan = new Scanner(System.in);
/**
* count the number of digits in a number
* #param num the number to analyse
* #return the number of digits it has
*/
public int numDigits (int num)
{
int nDigits = 0;
int digit;
while (num>0)
{
digit = num % 10; // take off the last digit
num = num /10; // reduce the number
nDigits = nDigits + 1; // increment count of digits
}
return nDigits;
}
/**
* Read a number from the keyboard, and report how many digits it has.
* Ensure the number is within a desired range.
*/
public void countDigits ()
{
int num=0;
while (num<1 || num > 1000)
{
System.out.print("What number (1 to 1000)? ");
num = scan.nextInt();
scan.nextLine();
System.out.println("Num = " + num);
if (num<1 || num > 1000)
System.out.println("1 to 1000, please");
}
System.out.println (num + " has " + numDigits(num) + " digits");
}
/**
* method used to if a number is the sum of the cube of its digits
* #param args (not used)
*/
public void sumCubesDigits ()
{
for (int initial = 1; initial < 1000; initial ++)
{
int num = initial;
int thirddig = num%10;
num = num / 10;
int secdig = num%10;
num = num / 10;
int firstdig = num%10;
int sum = (thirddig*thirddig*thirddig) + (secdig*secdig*secdig) + (firstdig*firstdig*firstdig);
if (sum == initial)
{
System.out.println ("The number " + initial + " is equal to the sum of the cube of its digits.");
}
}
}
/**
* Recieves an int and writes the same int backwards
* #param args (not used)
*/
public int backwards(int num)
{
int rev = 0;
int value = num;
while (value != 0)
{
rev = rev*10;
rev = rev + value%10;
value /= 10;
}
return rev;
}
/**
* Receives digit from method backwards
* Asses whether backwards = the original number
* #param args (not used)
*/
public boolean palindrome (int num, int digit)
{
boolean a = false;
int normal = num;
int reversed = digit;
if( reversed == digit)
{
a = true;
}
return a;
}
/**
* Recieves int from user - num
* Sends num to backwards
* Sends num to palindrome
* Recieves boolean from palindrome
* Outputs message to user
*/
public void checkPalindrome ()
{
System.out.println ("Enter number to be see if it is a palindrome");
int num = scan.nextInt();
int digit = backwards(num);
boolean check = palindrome (num, digit);
if (check = true)
{
System.out.println("Your number is a palindrome");
}
}
/**
* Present a menu to the user, and obtain their selection. If they
* type an erroneous value, report it and try again. Either upper
* case or lower case input is accepted.
* #return an upper case character showing the user's choice
*/
public char menuChoice ()
{
System.out.println("");
System.out.println("What do you want to do?");
System.out.println("(c) Count the digits in a number");
System.out.println("(g) Find out the numbers where the the sum of the cube of its digits is equal to it");
System.out.println("(p) Find out if a number is a palindrome");
System.out.println("(q) Quit");
System.out.print("Your choice? ");
char answer = ' ';
boolean ok = false;
while (! ok)
{
answer = scan.nextLine().trim().toUpperCase().charAt(0);
ok = (answer == 'C' || answer == 'Q' || answer == 'G' || answer == 'P');
if (! ok)
{
System.out.println("Please type one of c,C,q,Q,g,G,p,P");
System.out.print("Your choice? ");
}
}
return answer;
}
/**
* test driver for the program
*/
public void test()
{
char answer = ' ';
while (answer != 'Q')
{
answer = menuChoice();
switch (answer)
{
case 'C': countDigits(); break;
case 'G': sumCubesDigits(); break;
case 'P': checkPalindrome();break;
case 'Q': break;
}
}
}
/**
* main program: create a test driver and let it loose
* #param args (not used)
*/
public static void main (String [] args)
{
Lab1 l1 = new Lab1();
l1.test();
}
}
A StringIndexOutOfBoundsException is mostly thrown when you use charAt to select a character from a string that isn't there.
I guess your issue is here:
answer = scan.nextLine().trim().toUpperCase().charAt(0);
because that is the only charAt in your code.
What would that line do if the user entered nothing? Throw an Exception of course!
You should change if (check = true) to if (check == true) and answer = scan.nextLine().trim().toUpperCase().charAt(0); to answer = scan.nextLine();
if(answer != null)
answer = answer.trim().toUpperCase().charAt(0);

Creating a circular queue with arrays in 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;

Global Int variable method for multiple methods

I have to set up a math program that supplies random questions to the user based on their year level, and if they're doing well raise the difficulty. I've set up this code here that runs through questions and if they meet the requirements it displays the harder questions, however if "i" that i use to determinate how member questions they've done if separate the program will run the harder questions then go back and finish the easier questions
So basically I've tried to write a method for global "i" which all other methods will use, however when i replace "i" with the method it stops counting and continues to display questions infinitely and i don't know how to fix this.
import java.util.Scanner;
import java.util.*;
import java.util.Date;
public class Quiz {
public static void main(String[] args) {
int answer;
int correct;
double current_score = 100.00;
// int i = 0;
while (questionsDone() < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
System.out.print("What is the sum of" + " ");
System.out.print(random);
System.out.print(" + " + random2 + " ");
System.out.print("=" + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10.00);
}
System.out.println("Your current percentage is " + current_score); // end of result display
// i++; // raise number of questions given by 1
if (questionsDone() == 5 && current_score >= 75) { // code to move up or down year level
System.out.println("You are doing well! Let's increase the difficulty a little");
Year1_10Questions();
}
}
}
public static void Year1_10Questions() {
int i = 0;
int answer;
int correct;
double current_score = 100.00;
while (i < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
int random3 = (int) (Math.random() * 2 + 1);
String operator = "";
switch (random3) {
case 1:
operator = "+";
break;
case 2:
operator = "-";
break;
}
System.out.print("What is the sum of ");
System.out.print(" " + random + " ");
System.out.print(operator + " ");
System.out.print(random2 + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
if (random3 == 1) {
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
} else if (random3 == 2) {
correct = random - random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
}
System.out.println("Your current percentage is " + current_score); // end of result display
i++; // raise number of questions given by 1
}
} // end of year 1_10 questions
public static int questionsDone() {
int i = 0;
i++;
return i;
}
}
Since all the methods are in the same class, you can define i on class level:
public class Quiz {
static int i;
...
}

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