Printing the value and position of an array from a method - java

I am working on a program that takes user input for an array. One method I have FindLowestTempInArray returns the lowestDay (the position in the array). I want to print the index and the value at that spot in my main method. I have been searching and I dont know a simple way to do this. Right now I have been just been printing the data from the methods without returning the values. That works but I want to know how to print the values from the main. So once again all I am wondering is how to print both the lowestTemp and the lowestDay from the method in the main.
Here is my code I have:
public static int FindLowestTempInArray(int[] T)
{
// Returns the index of the lowest temperature in array T
int lowestTemp = Uninitialized;
int lowestDay = 0;
for(int day = 0; day < T.length; day++)
{
if(T[day] != Uninitialized && ( T[day] < lowestTemp || lowestTemp == Uninitialized))
{
lowestTemp = T[day];
lowestDay = day;
return lowestTemp;
}
}
return lowestDay;
}
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] high = new int[32];
int [] low = new int[32];
Init (high);
Init(low);
LoadData(high,low);
Report(high, low);
FindAvg(high);
//FindAvg(low);
//why do i not need to do both the one above and FindAvg(low);
System.out.println("The average for the high is: " + FindAvg(high));
System.out.println("The average for the low is: " + FindAvg(low));
//Lowest(high, low);
FindLowestTempInArray(high);
System.out.println(FindLowestTempInArray(high) + "\n" + FindLowestTempInArray(low));
Highest(high,low);
System.out.println("\n" + "The highest high is: " + Highest(high, low) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(high, low));
System.out.println("\n" + "The highest low is: " + Highest(low, high) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(low, high));
// LeastToGreatest(high, low);
}

There are 2 ways:
Change the return type of your FindLowestTempInArray to int[] i.e integer array and say int[0] islowest temperature and int[1] is lowest day
you can create a new class say Temperature with 2 class variables say temperature and day, and in your method FindLowestTempInArray you can have return type of Temperature and you can set the Temperature object in that method.
Below is sample of return type int[].
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
int[] lowest = new int[2];
lowest = FindLowestTempInArray(low);
System.out.println(lowest[0] + " " + lowest[1]);
}
public static int[] FindLowestTempInArray(int[] T) {
int[] lowest = new int[2];
lowest[0] = Uninitialized;
lowest[1] = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < lowest[0] || lowest[0] == Uninitialized)) {
lowest[0] = T[day];
lowest[1] = day;
}
}
return lowest;
}
}
Solution 2(Inner Class):
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
Weather.Temperature temp = FindLowestTempInArray(low);
System.out.println(temp.temperature + " " + temp.day);
}
public static Weather.Temperature FindLowestTempInArray(int[] T) {
Weather.Temperature temp=new Weather.Temperature();
temp.temperature = Uninitialized;
temp.day = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < temp.temperature || temp.temperature == Uninitialized)) {
temp.temperature = T[day];
temp.day = day;
}
}
return temp;
}
static class Temperature{
private int temperature;
private int day;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
}

One way would be to change the return type of public static int FindLowestTempInArray(int[] T) to int[], so that you can return both values. Otherwise, as soon as one return statement is executed, the method is exited.
You can use lowest[0] for the day and lowest[1] for the temp, or vice versa.
Another way is to get these two values separately (using parameters to distinguish which return value you want) and store them in two variables. The idea is to get these values stored somewhere in the main method to be able to play with them.
After you do that, you can use System.out to display the values, as desired.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Java array of queues printing out only last element within for loop in print method

I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.

My return values always equal 0

I coded multiple methods which use arrays to determine a certain value but they all result in 0 and I don't know why. The goal is to create a list of textbooks in a library and then return the heaviest book, weight, index, average page count and total page count.
public class Project3Driver {
// Data Fields
public static final int SUBJECTS = 5;
public static final int TEXTBOOKS = 10000;
String[] SUBJECT_LIST = {"Biology", "Calculus", "Linear Algebra", "Geology", "C++"};
Textbook[] library = new Textbook[TEXTBOOKS];
Random rand = new Random();
// Constructor that uses min-max system to randomize page count from 500-1500 and randomizes the subject
public Project3Driver() {
for (int i = 0; i < library.length; i++) {
library[i] = new Textbook(SUBJECT_LIST[rand.nextInt(SUBJECTS)], 500 + (int) (Math.random() * ((1500 - 500) + 1)));
}
}
// Methods
// Finds the heaviest book and returns the weight
public double findHeaviest() {
double heaviestBook = library[0].getWeight();
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook) {
heaviestBook = library[i].getWeight();
}
}
return heaviestBook;
}
// Finds the heaviest book and returns the index
public int getHeaviest() {
double heaviestBook = library[0].getWeight();
int index = 0;
for (int i = 1; i < library.length; i++) {
if (library[i].getWeight() > heaviestBook)
{
heaviestBook = library[i].getWeight();
index = i;
}
}
return index;
}
// Returns the average page count of the library
public int computeAverageSize() {
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
pageCount = pageCount / library.length;
return pageCount;
}
// Returns the total page count of the library
public int computeTotalPages()
{
int pageCount = 0;
for (int i = 0; i < library.length; i++)
{
pageCount = pageCount + library[i].getPageCount();
}
return pageCount;
}
// Tests each method and prints it (called in the main function)
public void getLibraryStats()
{
System.out.println("Heaviest book is " + library[getHeaviest()].getSubject());
System.out.println("The heaviest book is " + findHeaviest() + " kg");
System.out.println("The heaviest book is at the index " + getHeaviest());
System.out.println("The average book size is " + computeAverageSize());
System.out.println("There are " + computeTotalPages() + " pages total");
}
}
The getPageCount method simply returns the page count and getWeight returns the weight (by multiplying pageCount * 0.0025)
Any help would be greatly appreciated! I feel like it could be a problem with my arrays but I checked multiple times for errors
EDIT:
public class Textbook {
public static final double PAGE_WEIGHT = 0.0025;
public static final int PAGE_KNOWLEDGE = 5;
private String subject;
private int pageCount;
private int unreadPages;
// Start of Constructors
// Default constructor
public Textbook() {
subject = "Object-Oriented Programming";
pageCount = 800;
unreadPages = pageCount;
}
// Constructor with subject only
public Textbook(String textSubject) {
subject = textSubject;
}
// End subject constructor
// Constructor with subject and page count
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
unreadPages = pageCount;
} // End subject and page count constructor
// End of Constructors
// Start of Accessor Methods
// Method to return text subject
public String getSubject() {
return subject;
}
// Method to return page count
public int getPageCount() {
return pageCount;
}
// Method to return unread pages
public int getUnreadPageCount() {
return unreadPages;
}
// Method to get weight
public double getWeight() {
return pageCount * PAGE_WEIGHT;
}
// Method to read the pages
public int readPages(int numPages) {
if (numPages > pageCount) {
numPages = pageCount;
}
int knowledgeGained = 0;
if (unreadPages == 0) {
knowledgeGained = numPages * 5 / 2;
} else if (unreadPages <= numPages) {
knowledgeGained = unreadPages * 5 + (numPages - unreadPages) * 5 / 2;
unreadPages = 0;
} else {
knowledgeGained = numPages * 5;
unreadPages -= numPages;
}
return knowledgeGained;
}
}
public class CSC211Project3
{
public static void main(String[] args)
{
Project3Driver librarytester = new Project3Driver();
librarytester.getLibraryStats();
}
}
Your Textbook constructor doesn't initialize pageCount, so it will default to 0.
To fix it, initialize the field:
public Textbook(String bookSubject, int bookPages) {
subject = bookSubject;
pageCount = bookPages;
unreadPages = bookPages;
}
Try using a system out statement in the for loop to debug or debug with breakpoints.
Debugging with system out,
System.out.println("getting formed book weight "+library[i].getWeight())
There might be something wrong in the logic of the Textbook class constructor

Loop will not execute properly

I am writing a program for class and the loop seems to not execute correctly. It always returns the value for i as 0. The rest of the code seems to work as advertised, i is just not increasing in index value.
public class Day {
String strDay;
private int d = 0;
private String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String day;
public Day() {
return;
}
public Day(String strDay) {// this is my issue. I think I am going about this constructor all wrong
for (int i = 0; i < Days.length; i++) {
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
public int getDay() {
return d;
}
public void nexDay() {
int next;
if (d < 6) {
next = (this.d) + 1;
System.out.println("Next Day is :" + Days[next]);
} else {
next = 0;
System.out.println("Next Day is :" + Days[next]);
}
}
public void prevDay() {
int prev = 0;
if ((d > 0) && (d < 6)) {
prev = (this.d) - 1;
System.out.println("previous day is " + Days[prev]);
} else
System.out.println("previous day id " + Days[6]);
}
public int calcDay(int num) {
int newDay;
this.d = d + num;
newDay = this.d % 7;
System.out.println("calc day is" + Days[d]);
return newDay;
}
public void print() {
System.out.println("day is " + Days[d]);
}
public static void main(String[] args) {
String day;
Day Callmethod = new Day();
Scanner console = new Scanner(System.in);
System.out.println("enter a day of the week");
day = console.nextLine();
Callmethod.print();
Callmethod.nexDay();
Callmethod.prevDay();
Callmethod.getDay();
}
}
Well, this
Day Callmethod = new Day();
is calling your empty constructor. Not your constructor with a loop (which takes a String). Also, Java variables start with a lower case letter (Callmethod looks like a class). I think you were looking for something like
Day day = new Day("SUNDAY");
Also, your if needs braces or the return will be invoked without doing anything (unless it matches on the first entry) like
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i])) {
d = i;
return;
}
}
try change this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
for this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
{
d = i;
return;
}
}
}
Without the curly braces your conditional block will be only the next line of code. So your loop was only running once
public Day(String strDay) {
for (int i = 0; i < Days.length; i++) {
if (strDay == Days[i])
d = i;
return;
}
}
If I understood it clearly this will work. If not, just explain me what the goal is on that for loop. And place the return statement outisde of the next bracket.

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

Categories