I am very new to coding and I have a simple question. I want to input day, month and year inside a for loop and after inputting it I want to display all the inputted values on the same time. how to do it.kindly help me.
i have attached the code below.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++) {
int day = in.nextInt();
String month = in.next();
int year = in.nextInt();
}}
//need to display the entire content from the for loop
//suppose if the n value is 3
//i will be giving 3 inputs
//10 jan 1998
//11 nov 2000
//12 dec 1995
//i want to print all at the same time
Kindly help me with it.
If I understood your question correctly and you just want to print your inputs, just add the following to the loop:
System.out.println(String.format("%d %s %d", day, month, year));
or otherwise, but not as pretty (at least in my opinion):
System.out.println(day + " " + day + " " + month + " " + year);
EDIT
As indicated, you want to print them all at the same time. To do so, you can just save them all in a list or an array for example like the following:
Before the loop:
String[] dates = new String[n];
In the loop:
dates[i] = String.format("%d %s %d", day, month, year);
And then go ahead and insert another loop to print the content of the array:
for(String date: dates){
System.out.println(dates[i]);
}
From what I have gathered, you are looking to set a number on how many dates you'd like the user to enter, take in that number of dates and then print out the dates after the user input.
Here is some basic code that will do that for you
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int numOfInputs = 3; //How many separate dates you would like to enter
int day[] = new int[numOfInputs]; //declaring an integer array day and setting the array size to the value of numOfInputs
String month[] = new String[numOfInputs]; //declaring a string array month and setting the array size to the value of numOfInputs
int year[] = new int[numOfInputs]; //declaring an integer array year and setting the array size to the value of numOfInputs
//get inputs
for(int i=0;i<numOfInputs;i++) {
System.out.println("Please enter a day");
day[i] = sc.nextInt();
System.out.println("Please enter a month");
month[i] = sc.next();
System.out.println("Please enter a year");
year[i] = sc.nextInt();
}
//print content
for(int i=0;i<numOfInputs;i++) {
System.out.println(day[i] + " " + month[i] + " " + year[i]);
}
//close scanner
sc.close();
}
Let me know if this doesn't answer your question or if you need any clarification.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This program is supposed to add the hours from the input until the input ='s "done" but even after the input ='s "done" and the boolean is set to true in the while loop, it doesn't end the loop, and I can't figure out why. If someone inputs for example,
Friday
4
done
the code should output the day total and 4 as a result but it doesn't break the loop, and multiple inputs don't add the number of hours.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[]) throws Exception
{
// 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 hoursTotalString = "";
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);
hoursTotal= hoursTotal+hoursWorked;
prevDay = dayOfWeek;
System.out.println("\t" + DAY_FOOTER + String.valueOf(hoursTotal));
}
while(done == false){
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if( prevDay != dayOfWeek){
hoursTotal =0;
}
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
prevDay = dayOfWeek;
hoursTotal= hoursTotal+hoursWorked;
System.out.println("\t" + DAY_FOOTER + String.valueOf(hoursTotal));
if(dayOfWeek == "done"){
done = true;
break;
}
}
System.out.println(DAY_FOOTER + "(" + prevDay + ") " + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
The problem is your String comparetion, you shouldn't really compare two Strings with ==, but with .equals() method.
Just change this line:
if(dayOfWeek == "done") ...
to:
if(dayOfWeek.equals("done")) ...
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.
This question already has answers here:
How do you save user input inside an array?
(3 answers)
Closed 3 years ago.
I am a beginner programmer and I am making a little application for practice.
You enter your budget, then you add an expense(name, amount)
and it subtracts and tells you your current budget.
I want to make it so you can see all of your expenses after each execution.
I have tried to make for loops that store the names of the expenses and then print them.
But I am doing something wrong :/.
Sorry for my bad English, I am from Croatia!
Here is some beginner ugly code.
int length = 0;
String[] listOfNames = new String[length];
boolean active = true;
int budget = 0;
Scanner input = new Scanner(System.in); //user input
System.out.println("Enter current budget in HRK");
int enteredAmount = input.nextInt(); //user input for budget
budget = enteredAmount;
while(active)
{
System.out.println("Current budget is " + budget + " HRK");
System.out.println("Enter expense name and amount");
System.out.println("Name: ");
String name = input.next(); //name of expense
for(int i=0; i<listOfNames.length;i++){ //adds entered expense names to array
listOfNames[i] = name;
length++;
}
System.out.println("Amount: ");
int enteredAmount1 = input.nextInt();
budget -= enteredAmount1; // subtracts the budget from the users input
System.out.println("Expense: " + name + ", Amount: " + enteredAmount1); // prints final result
for(int j=0; j<listOfNames.length; j++) // prints stored strings in array
{
System.out.println(listOfNames[j]);
}
}
}
}
Here are the issues:
You started the length of listOfNames at zero.
int length = 0;
String[] listOfNames = new String[length];
That's why the for loops never run.
Also, it is not possible to change the size of an array in Java.
To store a variable amount of input, I recommend an ArrayList, which can be resized.
ArrayList<String> listOfNames = new ArrayList<String>();
Adding something to listOfNames:
String name = input.next();
listOfNames.add(name);
The downside to an ArrayList is that it is less efficient than an array, but this doesn't really matter for your program.
Here is the documentation and another helpful website for ArrayLists.
I'm having trouble with this array I'm working on. In the for loop, I need to somehow calculate an on base percentage. The element at index 0 will store the OBP. How can I retain the information the user inputs to calculate the OBP? Thank you.
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
I'd suggest a HashMap inside a HashMap for this use case.
Before loop:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
For every input from user's keyboard (example):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
In the end you get a result such as:
{2019={hits=5, walks=10}}
Retrieving results is simple too:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
You will want to store the values entered by the user in a variable. Instead of having an array of inputs (which is one way of doing it) - you can simply store each value in a separate variable and then do the calculation at the end.
See my sample code below:
public static void main(String args[]) {
// let's take incoming values from the user for our calculations
Scanner keyboard = new Scanner(System.in);
// we'll use this array to store the values entered by the user
// in position zero of the array we'll store the OBP
// in positions 1-5 we'll store the inputs as entered by the uesr
float[] values = new float[6];
// we'll use this flag to determin if we should ask the user input again or quit the program
boolean letsDoThisAgain = true;
while (letsDoThisAgain){
System.out.println("Enter a Year: ");
int year = keyboard.nextInt();
System.out.println("For Year " + year + ", enter number of:");
System.out.println("Hits: ");
values[1] = keyboard.nextFloat();
System.out.println("Walks: ");
values[2] = keyboard.nextFloat();
System.out.println("Number of times player has been hit by a pitch: ");
values[3] = keyboard.nextFloat();
System.out.println("Number of at bats: " );
values[4] = keyboard.nextFloat();
System.out.println("Number of sacrifice flies: ");
values[5] = keyboard.nextFloat();
// calculate the OBP
values[0] = (values[1] + values[2] + values[3] - values[5] ) / values[4]; // or however you calculate it
System.out.println("OBP: " + values[0]);
System.out.println("------");
System.out.println("Do you want to do it again? (y/n): ");
String quitOrDoItAgain = keyboard.next();
if( "n".equalsIgnoreCase(quitOrDoItAgain)){
letsDoThisAgain = false;
}
}
System.out.println("Thanks for playing... Good Bye!");
}
By the usage of a proper data structure like Map<string year, object playerstats> including OBP calculation on the object player stats before storing but this is an in-memory solution only last till the program is running if you like persistent then look on the database side
Also from the way you have presented your code it seems you are over-writing the value at year[index] always.
if you just want to use an array, then go like
years[index] = year[index] (math operation) keyboard.nextInt()
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.