Program doesn't step into method - java

I am trying to figure out why my program doesn't seem to be stepping into one of my methods: assignKennel(). Instead, it keeps asking for more input, even though theres more to do in the while loop. Any advice will be much appreciated. I'm not sure what to include, so here is all I have.
package finalbarking;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Finalbarking {
//global int numberOfDogs, numberOfKennels;
static int numberOfDogs, numberOfKennels=8;
//int dogID
static int [] dogIDs= new int [15];
//add provided ID's
//String dogNames
static String [] dogNames= new String [15];
//add provided dogs to array
//int dogWeights
static int [] dogWeights= new int [15];
//add provided weights to array
//at start, this is empty.
//array size = 8 elements myArray = new int[7]
//int KennelNumber
static int [] kennelNumbers= new int [8];
//String kennelWeight(SMALL / MEDIUM / LARGE)
static String [] kennelWeight= new String [3];
//int dogInKennelID
static int [] dogInKennelID= new int [8];
static int inputDogID=0;
public static void main(String[] args) throws InterruptedException {
//vars
//Scanner
Scanner response= new Scanner(System.in);
//int inputDogID
dogIDs[0]=1001;
dogIDs[1]=1003;
dogIDs[2]=1007;
dogIDs[3]=1008;
dogIDs[4]=1012;
dogIDs[5]=1034;
dogIDs[6]=1038;
dogIDs[7]=1087;
dogIDs[8]=1088;
dogIDs[9]=1120;
dogIDs[10]=1129;
dogIDs[11]=1145;
dogIDs[12]=1200;
dogIDs[13]=1211;
dogIDs[14]=1222;
dogNames[0]= "Bowser";
dogNames[1]= "Ginger";
dogNames[2]= "Molly";
dogNames[3]= "Murphy";
dogNames[4]= "Roxy";
dogNames[5]= "Samantha";
dogNames[6]= "Duke";
dogNames[7]= "Pookie";
dogNames[8]= "Abby";
dogNames[9]= "Barney";
dogNames[10]= "Autumn";
dogNames[11]= "Hershey";
dogNames[12]= "King";
dogNames[13]= "Bosco";
dogNames[14]= "Daisy";
dogWeights[0]=130;
dogWeights[1]=80;
dogWeights[2]=45;
dogWeights[3]=18;
dogWeights[4]=70;
dogWeights[5]=12;
dogWeights[6]=90;
dogWeights[7]=16;
dogWeights[8]=35;
dogWeights[9]=65;
dogWeights[10]=20;
dogWeights[11]=100;
dogWeights[12]=110;
dogWeights[13]=70;
dogWeights[14]=55;
kennelWeight[0] = "SMALL";
kennelWeight[1] = "MEDIUM";
kennelWeight[2]= "LARGE";
//reset at end
//Greeting for employee
System.out.println("Hello Barking Lot Employee!");
//begin loop
while(inputDogID!=9999){
//try
try{
//prompt for dog id, 9999 as sentinel value
System.out.println("Please enter the dog's ID number, or '9999' to quit)");
//capture
inputDogID= response.nextInt();
//end try start catch exception
}catch(InputMismatchException error){
//Invalid
System.err.println("You've entered an invalid Dog ID. Try again(Please refer to our Dog Client List, they are all 4 digits long).");
//pause program
Thread.sleep(10);
//reset scanner
response = new Scanner(System.in);
}//end catch
int foundDogID = 0;
for(int count=0; count<15; count++)
{
if(dogIDs[count] == inputDogID){
foundDogID = count;
}//end if
}//end for
currentClients(dogIDs,dogNames,dogWeights,inputDogID);
//assignKennel()
assignKennel(foundDogID);
//displayKennel();
displayKennel();
}//endwhile
}//end main
//User Defined Methods
//CurrentClients- Identifies dog based on list of current clients
public static void currentClients(int[]dogIDs,String[]dogNames,int[]dogWeights,int inputDogID){
//Takes 3 arrays(ID, NAME, WEIGHT)
//Takes inputDogID
//Iterate the array and check if inputDogID == ID[count]
//for(int count = 0; count < numberOfDogs; count++)
for(int count = 0; count <= numberOfDogs; count ++){
//if(inputDogID == ID) then return NAME + WEIGHT;
if(inputDogID==dogIDs[count]){
System.out.println("Dog Name : "+dogNames[count]+"\tDog Weight: "+ dogWeights[count]);
}//end if
//else then return 0 and display an error
else
System.out.println("Did not find a dog matching this ID Number.");
}//end for
}//endCurrentClients
//assignKennel-assigns dogs to kennels
public static void assignKennel(int dogIDs){
//takes 1 int dogID
//Iterate the array and check:
//var
boolean didDogGetKennel=false;
for(int count = 0; count < numberOfKennels; count++){
//if(getDogWeightClass(dogWeights[dogID]).equals(kennelWeight[count]))
String weightClass = getDogWeightClass(dogWeights[dogIDs]);
for(int counter = 0; counter < 3; counter++)
{
if(weightClass.equals(kennelWeight[counter]))
{
if(dogInKennelID[count] == 0){
//then EMPTY, assign
didDogGetKennel=true;
dogInKennelID[count]=dogIDs;
}//end if
}
}
}//end for loop
//if didDogGetKennel=false display message: "I'm sorry all ken
if(didDogGetKennel==false)
System.out.println("I'm sorry, all of our kennels for that weight limit are filled.");
}//end assignKennel
//displayKennel- displays the eight kennel numbers &the dog assigned to each
public static void displayKennel(){
// print if all kennels are filled
if(areKennelsFull()){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end if
//else if print if sentinel value is enter
else if(inputDogID==9999){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end else if
}//end displayKennel
//getDogWeightClass()
public static String getDogWeightClass(int dogWeight){
//take int dog weight
//if dog weight < 50, then SMALL
if(dogWeight<50)
return "SMALL";
//else if dog weight >50 &&<100 then MEDIUM
else if(dogWeight>50 &&dogWeight <100)
return "MEDIUM";
//else then LARGE
else
return "LARGE";
//return String S/M/L
}//end getDogWeightClass
//getDogName()
public static String getDogName(int dogInKennelID){
//take dogInKennelID
return dogNames[dogInKennelID];
}//end getDogName
//areKennelsFull()
public static Boolean areKennelsFull(){
for(int count =0; count<=8; count ++){
if (dogInKennelID[count] ==0)
return false;
//return boolean false
//else return boolean true
else
return true;
}//end for
return false;
}//end areKennelsFull
}//end class

It actually does run assignKennel(). If you put a System.out.println() statement in there to verify that that method runs, you'll see that it does. The problem isn't with that method; every method is running as it should.
Your problem is in displayKennel(). It isn't doing anything. areKennelsFull() evaluates to false, as does inputDogID==9999 (assuming some other id was typed in). I'm guessing areKennelsFull() is supposed to evaluate to true after a valid ID has been entered, so the root cause of this problem is most likely either in areKennelsFull() or perhaps in assignKennels() incorrectly assigning a value somewhere in dogInKennelID.

It does enter that routine, but one problem I see is that you are exceeding the array index. You have the condition "count<=8" in 3 for statements which should read "count<8" (remove the "="). When it tries to use index 8, it bombs, and so the program cannot finish properly. The array is indexed from 0 to 7, so 8 is invalid.

Related

Trying to set array elements constraints

1.Output: print remainder when sum is divided by max element.
2.Constraints: 1<=n<=100;
0<=A[i]<=1000
I need this code to validate array elements as such:
pseudocode:
if (arr_elmt>=0 and arr_elmt<=1000) ->Then execute succeeding commands.
else ->stop program, even though other elements obey constraint
3.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
int i=0;
for(i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(i=0;i<A.length;i++)
{ //Second constraint
if(A[i]>=0 && A[i]<=1000)
{
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(i=0;i<A.length;i++)//i=1 can work
{
if(A[i]>largest)
{
largest=A[i];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.print("\n"+ rem);
}
}
}
}
}
e.g: input: 3;
Values: 2988 67 5.
I expect an error due to 2988>1000, but the code
still runs and gives me output! output obtained:(2988+67+5)mod(2988)
Hi so your problem is that you do not specified that program should stop (or do whatever you want) when find number which does not match your second constraint.
So right now when does not match second constraint for 2688 it keeps iterating to second item and keep executing rest of your code.
So to make your program end when second constraint is not match you should add something like this
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
for(int i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(int i=0;i<A.length;i++)
{ //Second constraint loop through all elements of A[]
// if one of it does not obey constraint exit the program
if(A[i]<=0 || A[i]>=1000) // notice here I change '>'
{
System.exit(0); // this else is attached to your second constraint
}
}
for(int i = 0; i < A.length; i++){
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(int j=0;j<A.length;j++)//i=1 can work
{
if(A[j]>largest)
{
largest=A[j];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.println(rem);
}
}
}
}

Generate random integers with a range and place them into this array

I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}

IndexOutOfBoundsException error adding long numbers

I am trying to wrtie java application that adds up to 5 long numbers using LinkedLists. At the end of the run I get this:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:
0, Size: 0
at java.util.LinkedList.checkElementIndex(LinkedList.java:555) at java.util.LinkedList.remove(LinkedList.java:525) at
Assignment1.LongNumbers.remove(LongNumbers.java:33) at
Assignment1.LongNumbers.main(LongNumbers.java:92)
Here is the code:
import java.util.*;
/**
*
* #author .....
*/
public class LongNumbers
{
private List<Integer> [] theLists;
public LongNumbers() {
this.theLists = new LinkedList[6];
for (int i=0; i<6; i++)
this.theLists[i]= new LinkedList<>();
}
public void add(int location, int digit) {
//add digit at head of LinkedList given by location
theLists[location].add(digit);
}
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
public boolean isEmpty(int location) {
//check for an empty LinkedList given by location
return theLists[location].isEmpty();
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
//Local Variables
int digit;
int carry = 0;
int numberAt = 0;
int largestNumLength = 0;
char[] digits;
String number;
boolean userWantstoQuit = false;
LongNumbers Lists = new LongNumbers();
System.out.println("The program will enter up to 5 numbers and add them up.");
System.out.println();
while(!userWantstoQuit && numberAt != 5){
System.out.print("Enter a number, enter -1 to quit entry phase: ");
number = stdIn.nextLine();
if((number.compareTo("-1")) == 0)
userWantstoQuit = true;
else{
digits = new char[number.length()];
for(int i=0;i<number.length();i++)
digits[i] = number.charAt(i);
for(int i=0;i<number.length();i++){
int tempValue = digits[i] - 48;
try{
Lists.add(numberAt, tempValue);
}
catch(NumberFormatException nfe){
System.out.println("Invalid Input. Please try again.");
break;
}
if(i == (number.length() - 1))
numberAt++;
if(number.length() > largestNumLength)
largestNumLength = number.length();
}
}
}
for(int j=0;j<largestNumLength;j++){
int tempDigit = 0;
int index = 0;
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
digit = carry + tempDigit;
if(j < numberAt){
carry = digit/10;
digit = digit%10;
}
Lists.add(5, digit);
}
System.out.print("The sum of the numbers is: ");
for(int i=0;i<Lists.theLists[5].size();i++){
System.out.print(Lists.theLists[5].get(i));
}
System.out.println();
System.out.println();
System.out.println();
}//end main
}//end class
For starters, I don't think you can have an array of List<E> objects...
You should also make sure your list is initialized and has an item at the given location.
So your method might look something like this:
public int remove(int location)
{
if(theLists != null)
if(theLists.size() > location)
return theLists.remove(location);
return 0;
}
If you need 2 dimensions of lists, you could try using List<List<E>>
Treat all E as Integer.
Look at the code here:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
You are checking whether the first element of the index'th list is not null. If that is true, you are adding it and call the remove method. However, what if you already processed the first list and index'th value is 1? In that case theLists[1].get(0) != null is true, but Lists.remove(0) passes 0 as location. Take a look at this code:
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
In the scenario I have described, location is 0. But your 0'th list is already empty...
EDIT: Rewrite the remove method, like this:
public int remove(int location, int index) {
//remove a digit from LinkedList given by location
return theLists[index].remove(location); //LongNumbers.java:33
}
And whenever you call this method, pass the index of the list to work with. Example:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0, index); //LongNumbers.java:99
}
index++;
}
Finally: In the future, please, structure your code, it was a real pain to read it in this, unstructured state, read about how to code.

Extras values after calling main method

This program works fine if i enter the correct value (int value). However, when I enter in a character or any other wrong value it displays the wrong input message and calls the main method again. The only problem is after calling the main method and inputting the correct input it prints out extra data why is that?
import javax.swing.JOptionPane;
public class TestPolyVal {
public static void main(String[] args){
int xValue = 0;
String value = JOptionPane.showInputDialog(null, "What is the value of X");
try{
xValue = Integer.parseInt(value);}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
}
int[] intArray = new int[20] ;
for (int i = 0; i < 20; i ++){
intArray[i] = 2;}
System.out.println(calculateBruteForce(intArray,xValue));
System.out.println("0");
System.out.println(calculateHorner(intArray,xValue));}
static int calculateBruteForce(int[] a, int b){
int sum = 0 ;
for (int i = 0; i < 20; i ++){
sum +=a[i]*powerCalc(b,i);}
return sum;}
static int powerCalc(int c, int d){
int powerValue = c;
if (d==0){
powerValue = 1;}
else if (d==1){
powerValue = c;}
else if (d>1){
for (int i = 1; i<d;i++){
powerValue = powerValue*c;}}
return powerValue;}
static int calculateHorner(int[] e, int f){
int acc = e[e.length-1];
for(int i = e.length-2; i >= 0; i--){
acc = (acc * f)+ e[i];}
return acc;}
}
You are getting extra printouts because the first main execution will continue after the second main invocation is done.
This can be fixed by adding a return; after the new call to main:
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
return;
}
The approach of calling main() from within main() is not a great approach in this case. I, as an adversarial user, could just type 'a' in the dialog over and over again. Eventually this would cause a Stack Overflow Error and your program would crash.
I would suggest using a loop.
while(true) {
try{
xValue = Integer.parseInt(value);
break;
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
}
}
This way your program would just loop forever or until the user enters correct input instead of crashing. Unless you're implementing a recursive algorithm, I can't think of any reason for a method to invoke itself.

Sorting multiple arrays within a file. Putting states population in order

**This is my first post so don't know if I did this right. But I have to read a file and then put the list in order from smallest to largest by the population. All I get is Alabama and that shows up only one time. I think my problem is from the "for" statement but I am not sure. It could also be from the "return" statement. The file is set up like this
Alabama,4779736
Alaska,7102313**
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Inorder {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
PrintWriter prw = new PrintWriter("outfile.txt");
File f = new File("census2010.txt");
if(!f.exists()) {
System.out.println( "f does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+");
final int MAX = 50;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
fillsize = fillarray (myarray, statearray, infile);
printarray (myarray, fillsize, prw);
sortarray(myarray, statearray, fillsize);
}
public static int fillarray (int[] num, String[] states, Scanner infile){
for( int count = 0; count < 50; count++){
int retcnt = 0;
int pop;
String state;
state = infile.next();
pop = infile.nextInt();
System.out.println(state + " " + pop + " ");
states[retcnt] = state;
num[retcnt] = pop;
retcnt++;
return (retcnt); }
}
public static void printarray (int[] num, int fillsize, PrintWriter prw){
for (int counts = 0; counts < fillsize ; counts++){
System.out.println("For the position ["+counts+"] the value is " + num[counts]);
prw.println("For the position ["+counts+"] the value is " + num[counts]);
}
return;
}
public static void sortarray(int[] poparray, String[] statearray, int fillsize){
for( int fill = 0; fill < fillsize -1; fill = fill+1){
for ( int compare = fill+1; compare < fillsize; compare++){
if( poparray[compare] < poparray[fill]){
int poptemp = poparray[fill];
poparray[fill] = poparray[compare];
poparray[compare] = poptemp;
// do I need something here?
String statetemp = statearray[fill];
statearray[fill] = statearray[compare];
statearray[compare] = statetemp;
}
}
}
}
}
It looks like you just need to move your return statement outside of the for loop.
public static int fillarray (int[] num, String[] states, Scanner infile){
for( int count = 0; count < 50; count++){
// ...
} // Finish *all* iterations of the loop, *then* return
return (retcnt);
}
By having a return inside your loop, you only execute the first iteration and the method returns (preventing all other 49 iterations). You do this correctly in your printarray method.
Edit:
As you mentioned, moving the return statement outside of your loop makes it so that retcnt is no longer accessible. This is because you declare retcnt inside the loop; if you declare retcnt before the loop, you will have no problems.
int retcnt = 0;
for (//...) {
//...
}
// The variable retcnt is now accessible for the entire method scope,
// instead of just the loop block
return retcnt;

Categories

Resources