Array Length Outcome - java

My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02

If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.

Related

I need help to print out between what prices the largest absolute difference occurred in the program. (I'm nearly finished.)

I can't figure out the right way to update the prices during the if condition. It's probably really simple but I'm having trouble with it. Here is my code.
public class Change {
public static void main(String[] args) {
final int days = 10;
int largeDiff = 0; // largest difference
int price2 = 0;
int day1 = 1;
int day2 = 2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter stock prices:");
int price1 = sc.nextInt();
for (int i = 2; i <= days; i++) {
price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
price1 = price2;
if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
}
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + price1 + " to " + price2);
System.out.println("happened between day " + day1 + " and day " + day2);
}
}
Your problem is the line
System.out.println("from " + price1 + " to " + price2);
because by the end of your loop, price1 and price2 will both be just the last price entered.
What you need to do is when you store values for largeDiff, day1 and day2, you should also store values for the two prices. Then at the end of the loop, print those stored values instead of price1 and price2.
price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
storedPrice1 = price1;
storedPrice2 = price2;
}
price1 = price2;
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + storedPrice1 + " to " + storedPrice2);
I would use an array to store the values
final int price1 = sc.nextInt();
int[] prices = {price1, 0};
int[] days = {day1, 0};
for (int i = day2; i <= days; i++) {
price2 = sc.nextInt();
int newDiff = Math.abs(price1 - price2);
if (newDiff > largeDiff) {
largeDiff = newDiff;
days[1] = i;
prices[1] = price2;
}
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + prices[0] + " to " + prices[1]);
System.out.println("happened between day " + days[0] + " and day " + days[1]);
But I don't trust that loop over the days because if you wanted the largest price between all possible date pairs, you want something like
for (int day1 = 0; day1 <= days; day1++) {
// Get day1 price
for (int day2 = 0; days2 <= days; day2++) {
if (day1 == day2) continue; // skip the same day
// Get day2 price
// Get price between days
// Check against largestDiff
// Store diff, day1, day2, and the prices
}
}

I want to find max and min values in java

I want max and min values of salary to display but i get same values for max and min. Here's my code:
import java.util.*;
class Wage {
String employee_name, skill;
int hours;
double sum;
String[] sno = {"1", "2", "3", "4"};
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
Scanner s = new Scanner(System.in);
public void getEmployeeDetails() {
System.out.println("Welcome to Use General Wage Record System");
for (String count : sno) {
if (count.equalsIgnoreCase("1")) {
System.out.print("Enter Name of Employee 1: ");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("2")) {
System.out.print("Enter Name of Employee 2:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee " + employee_name + "(Level " + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("3")) {
System.out.print("Enter Name of Employee 3:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " $" + sum);
}
}
if (count.equalsIgnoreCase("4")) {
System.out.print("Enter Name of Employee 4:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + "$ " + sum);
}
}
}
}
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
if (sum > max) {
max = sum;
System.out.println("Maximum of wage" + max + ", " + employee_name);
}
if (sum < min) {
min= sum ;
System.out.println("Minimum of Wage" + min + ", " + employee_name);
}
}
}
public class Pay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Wage wm = new Wage();
wm.getEmployeeDetails();
wm.average();
}
In the loop of the getEmployeeDetails() method, you don't store and update the min wage, the max wage and the employee names that have these wages.
Besides, you should be more specific in the naming. For example, maxWage and minWage are more meaningful than max and min.
So, you should have maxWage, maxWageEmployeeName, minWage and minWageEmployeeName fields in the field declaration of the Wage class.
At each employee inserted in the system, you should update these values by calling a dedicated method:
public void getEmployeeDetails() {
if (count.equalsIgnoreCase("1")) {
....
updateRanking(sum, employee_name);
}
}
public void updateRanking(double actualWage, String employee_name){
if (actualWage > maxWage) {
maxWage = actualWage;
maxWageEmployeeName = employee_name;
}
else if (actualWage < minWage) {
minWage = actualWage;
minWageEmployeeName = employee_name;
}
}
Besides, your average() method called at the end of your program should only display the result and not performing comparison since you should have updated information about max, min wage and who have these as updateRanking() is called at each insertion of employee wage :
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
System.out.println("Maximum of wage" + maxWage + ", " + maxWageEmployeeName );
System.out.println("Minimum of Wage" + minWage + ", " + minWageEmployeeName );
}

Cannot Print Number of Digits Correctly

For my current programming project I am supposed to format my testOne & testTwo like "000". While the average is supposed to be "000.0". I have used DecimalFormat to no avail. Furthermore for my letterGradeArray the letter won't display even though the letter grade is in the actual array. Here is my code:
import java.util.Scanner;
//import java.text.NumberFormat;
import java.text.DecimalFormat;
public class GradeArray
{
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args)
{
//Setup all the variables
Scanner scan = new Scanner(System.in);
int[] testOne = new int[4]; // Students’ test one grades
int[] testTwo = new int[4]; // Students’ test two grades
double[] average = new double[4]; // Students’ average grades
double z = 002.00;
char letterGrade = 0;
char[] letterGradeArray = new char[4];
DecimalFormat fmt1 = new DecimalFormat("000");
DecimalFormat fmt2 = new DecimalFormat("000.0");
//Begin asking for scores
System.out.println("For test 1,");
for (int i=0;i<testOne.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testOne[i] = scan.nextInt();
fmt1.format(testOne[i]);
}
System.out.println("\nFor test 2,");
for (int i=0;i<testTwo.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testTwo[i] = scan.nextInt();
fmt1.format(testTwo[i]);
}
//Compute average
for(int i=0;i<average.length;i++)
{
{
average[i] = (testOne[i]+testTwo[i])/z;
fmt2.format(average[i]);
}
}
//Compute letter grade
for(int i=0;i<average.length;i++)
{
if (average[i]>= 90 )
{
letterGrade = 'A';
} else if (average[i] >= 80) {
letterGrade = 'B';
} else if (average[i] >= 70) {
letterGrade = 'C';
} else if (average[i] >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
//Put the letterGrade into the letterGradeArray
for(int x=0;i<letterGradeArray[x];x++)
{
letterGradeArray[x]=letterGrade;
}
}
//Print it out
System.out.println("Test 1 Test 2 Average Grade");
System.out.println("______ ______ _______ _____");
System.out.println(testOne[0] + " " + testTwo[0] + " " + average[0] +" " + letterGradeArray[0]);
System.out.println(testOne[1] + " " + testTwo[1] + " " + average[1] +" " + letterGradeArray[1]);
System.out.println(testOne[2] + " " + testTwo[2] + " " + average[2] +" " + letterGradeArray[2]);
System.out.println(testOne[3] + " " + testTwo[3] + " " + average[3] +" " + letterGradeArray[3]);
}
}
If anyone has any ideas on how to make this code cleaner do tell me, I feel with all the fors it is clunky.
You are calling fmt1.format(testOne[i]); but you are not doing anything with the result. Calling format returns a String, it does not affect the thing being passed as a parameter, so when you later print testOne[0] etc. you are printing the plain, original, values.
If you want the formatted values you will have to assign the return of .format() to something, keep it around, and print it instead of the original integer values. For example, patterned after how the rest of your code works...
String[] formattedOne = new String[4];
// ... later
formattedOne[i] = fmt1.format(testOne[i]);
// ... still later
System.out.println(formattedOne[0] + " " ..........

Searching an array for term and if statements

I have code that searches for a term in a string and want it to find it then it counts and outputs the total. I am trying to search for another term and output the total of that term.
For example:
for(String[] passenger : passengerList) {
if(passenger[3].equalsIgnoreCase("female")) {
allFemale++;
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1 {
femaleSurvivors++;
}
}
count ++;
}
System.out.println("The number of females who survived: ");
return femaleSurvivors;
}
Now, I want to search for the male and count the times that occurs. Not having any luck.
You would really need to keep track of 4 things, sex (m/f) and status (dead/alive). You can do it all in a single loop. Part of it can be captured in the loop, and part of it could be calculated after the fact.
int survivors = 0;
int femaleSurvivors = 0;
int femaleDeaths = 0;
for(String[] passenger : passengerList) {
boolean isFemale = false;
if(passenger[3].equalsIgnoreCase("female")) {
isFemale = true;
}
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1) {
survivors ++;
if (isFemale){
femaleSurvivors++;
}
} else {
if (isFemale){
femaleDeaths++;
}
}
}
int totalPassengers = passengerList.size();
int maleSurvivors = survivors - femaleSurvivors;
int deaths = totalPassengers - survivors;
int maleDeaths = deaths - femaleDeaths;
int males = maleSurvivors + maleDeaths;
int females = totalPassengers - males;
System.out.println("Survivors (Total/M/F): " + survivors + "/" + maleSurvivors + "/" + femaleSurvivors);
System.out.println("Deaths (Total/M/F): " + deaths + "/" + maleDeaths + "/" + femaleDeaths);
System.out.println("Totals (All/M/F): " + totalPassengers + "/" + males + "/" + females);

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

Categories

Resources