Trouble with Displaying 1D Array Output Correctly - java

My program consists of several options of what to do with user input data about shows (name, day, time). One of the options is to display the data and the total number of shows per day (ex: if there are 2 shows on Tuesday, it will display "There are 2 shows on Tuesday"). So far the output for displaying all the data is working but when it comes to displaying the number of shows on a specific day, it isn't working properly. I've read several other java programs that seem to have a switch statement on each day but that hasn't worked either. If there are any suggestions on what I should change about my code, I would truly appreciate it! Thank you
I have edited my code from the previous one but it still hasn't worked
Note: the int dayCount is placed in the enter data method; after the day[i] = br.readLine();
Here is my class:
import java.io.*;
public class Javavision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String name[] = new String[1000];
static String day[] = new String[1000];
static String time[] = new String[1000];
static int dayCount = 0;
static int x, i, j, smallest;
static String temp;
Here is my code:
public static void showShows() {
//output all shows
for (i = 0; i < x; i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
} **The problem is here**
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
}
Here is the output:
Name : The Flash
Day : Sunday
Time(2:30 am = 0230) : 0125
Name : Suits
Day : Sunday
Time(2:30 am = 0230) : 0450
Name : Java Program
Day : Tuesday
Time(2:30 am = 0230) : 0330
There is 3 shows on Sunday
This is where I increment dayCount:
//Method addShow
public static void addShow() throws IOException {
//initialize counter
x = 0;
do {
//Update Array
System.out.println("Enter Name of Show: ");
name[x] = in.readLine();
System.out.println("Enter Day of Show: ");
day[x] = in.readLine();
dayCount++;
System.out.println("Enter Time of Show (ex: 2:30am = 0230) : ");
time[x] = in.readLine();
//Increase counter
x++;
//Ask if the user wants to stop
System.out.println("\nTo continue press Enter ");
System.out.println("To Quit, type in 'quit': ");
}
while((in.readLine().compareTo("quit"))!=0);
//Method addShow()
}

In your loop that prints the total shows you have:
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
The if(i == 0) makes it so that the println only executes on the first iteration of the loop. Take out the if statement and have:
for (i = 0; i < x; i++) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
And this should print out the rest of the days
Also you only have one dayCount variable that you use for all the days. So no matter what day a show is on, you increment dayCount. (If you have three shows on different days you still increment dayCount everytime so it shows that you have three shows on each day when you print it out) If you want to have a separate dayCount variable for every day, I recommend using a Hashmap.
(Using the day as the key and the dayCount as the value)
Also you could look into enums to use for the days of the week.

Related

Why is my code is outputing thousands of times?

I am supposed to make this code output Day total and then the number of hours worked for that day. The code is currently displaying the day and the total. But it is displaying too many times for the program to even register. For instance, it asks to input a day, and I'll put in Monday. Then the number of hours worked, and I'll put 6. It will then output Monday 6.0 thousands of times. The expected output should be Day Total 6. What am I missing or is added to cause this?
// SuperMarket.java - This program creates a report that lists weekly hours worked
// by employees of a supermarket. The report lists total hours for
// each day of one week.
// Input: Interactive
// Output: Report.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[])
{
// Declare variables.
final String HEAD1 = "WEEKLY HOURS WORKED";
final String DAY_FOOTER = " Day Total "; // Leading spaces are intentional.
final String SENTINEL = "done"; // Named constant for sentinel value.
double hoursWorked = 0; // Current record hours.
String hoursWorkedString = ""; // String version of hours
String dayOfWeek; // Current record day of week.
double hoursTotal = 0; // Hours total for a day.
String prevDay = ""; // Previous day of week.
boolean done = false; // loop control
Scanner input = new Scanner(System.in);
// Print two blank lines.
System.out.println();
System.out.println();
// Print heading.
System.out.println(HEAD1);
// Print two blank lines.
System.out.println();
System.out.println();
// Read first record
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if(dayOfWeek.compareTo(SENTINEL) == 0)
done = true;
else
{
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
hoursWorked = Integer.parseInt(hoursWorkedString);
prevDay = dayOfWeek;
}
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
System.out.println(dayOfWeek + " " + hoursWorked + hoursTotal);
hoursTotal++;
if(dayOfWeek.compareTo(SENTINEL) == 0)
{
hoursWorked = dayOfWeek.compareTo(SENTINEL);
prevDay = dayOfWeek;
done = true;
}
else
done = false;
// Include work done in the dayChange() method
if(dayOfWeek.compareTo(SENTINEL) == 0)
System.out.println(DAY_FOOTER + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
In this code block, you aren't changing done variable, so it is an infinite loop.

how do I reprint the loops output, outside the loops

Problem:
How do I reprint the for-loops output, outside the loop? Need help to figure it out. what seems to be the error?
Research effort:
**import java.util.*;
public class Admin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList <String> title = new ArrayList<>();
String n = in.nextLine();
int i = 0;
int j = 0;
while(!n.equals(" ")){
System.out.println("Enter a movie title");
title.add(n);
n = in.nextLine();
}
for(;i < title.size(); i++){
System.out.println("[" + i +"]" +title.get(i));
}
int [] price = new int [title.size()];
for(;j < price.length; j++ ){
System.out.println("Enter price for");
price[j] = in.nextInt();
System.out.println("Price for ["+j+"] is "+ price[j] );
}
//the problem
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
}
}
every time I run it after the loops, error shows up
Expected Result: is that it will print the "i" and "title[i]" together with the "j" and "price[j]" both outside it's loops
If I understood you correctly you want to see something like this:
[0]MovieTitle1 Price: MoviePrice1
[1]MovieTitle2 Price: MoviePrice2
There are some Problems: At first, you are going to get an IndexOutOfBoundsException,
because i and j have been increased to title.size(). This is because of the two for-Loops.
In my example this means that i == 2 and j == 2 are true after execution of both for-Loops has happened.
The title ArrayList and the price Array know the Entrys 0 and 1 (in my example) - you are trying to access Entry 2 which is out of bounds.
A possible solution would be to change this:
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
to something like this:
for(int n = 0; n < title.size(); n++) {
System.out.println("[" + n + "]" + title.get(n) + " Price: " + price[n]);
}

Not printing correctly, but still running

import java.util.Scanner;
import java.util.Random;
public class ResponseTimeProject
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter your full name: ");
String name = in.nextLine();
System.out.println("Hello " + name + ". Please answer as fast as you can." + "\n\nHit <ENTER> when ready for the question.");
in.nextLine();
for (int count = 0; count < 4; count ++) {
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int character=(int)(Math.random()*26);
String s = alphabet.substring(character, character+1);
Random r = new Random();
int i;
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
long startTime = System.currentTimeMillis();
System.out.print("What is the next letter in the alphabet?" + " ");
String response = in.nextLine();
long endTime = System.currentTimeMillis();
String outcome;
if (alphabet.substring(character+1, character+2).equals(response)) {
outcome = "Correct!";
} else {
outcome = "Incorrect.";
}
long reactionTime = endTime - startTime;
System.out.println(outcome);
System.out.println("The average time it took you was " + reactionTime + " milliseconds");
System.out.println("Thank you " + name + ", goodbye.");
}
}
}
HELP:
This code runs but it gives me the wrong answer. I do not know what is wrong. It prints incorrect for the right outcome. Not sure what I need to fix
The code in question is really a total mess (substring to get a character from a String, loops of a single iteration, etc.). But the fundamental issue relating to the question is that the "next letter in the alphabet" depends upon an output that is printed but never stored. It is currently
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
and therefore never saved, so there is nothing to compare it to.
So, save the next character, and then print it.
char nextLetter = alphabet.charAt(r.nextInt(alphabet.length());
Then in the comparison, for the response, check the response against an actual value, not some random substring from the alphabet String.
response = in.nextLine();
char chkChar = response.charAt(0);
if (chkChar == nextLetter) {
...
}

Reading a string, printing a name and adding integers

so I am to write a method through Java that will read a file input, print a string that is a name, and sum up golf scores. I am literally stumped and can not think of how to do this. I have a main method that has been given and is not to be altered. This leaves me with another method to do all the work. Thus far I have,
public static void computeScores(Scanner file) {
int numGolfers = file.nextInt();
// add your code here
int highScore;
int totalScore = 0;
boolean beatPar;
beatPar = totalScore <= 72;
System.out.print("Number of golfers: " + numGolfers + "\n\n");
System.out.println("NAME SCORE TO PAR");
System.out.println("---- ----- ------");
for (int i = 1; i <= numGolfers; i++) {
String golferName = file.next();
boolean isLineOver = golferName == "\n";
while (isLineOver) {
int score = file.nextInt();
if () {
totalScore += score;
}
System.out.print(totalScore);
}
String nextGolfer = file.nextLine();
System.out.println(golferName + " " + totalScore);
//System.out.println(nextGolfer);
}
if (beatPar) {
System.out.println("At least one golfer scored par or below.");
}
}
I have only been able to output the names, and sometimes the first number from a list of 18 numbers. Sorry about the extraneous code that's been commented out.
Any kind of pointers would be appreciated.
The file I have been given has information in the following format
Name 1 2 3 4 5 etc.
change golferName == "\n" to golferName.equals("\n") for Strings

Identifying if the user presses <enter>

I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement

Categories