I was asked to write a program that will input the employee's id number, time in and time out. The data would be written in a .txt file. I understand that im supposed to use FileWriter but might I ask if its possible to tab the information? Id like to make my .txt file something like this:
Name Time in Time out Total hours worked Salary
Name1 08:00 05:00 9 4000
Name2 09:00 04:00 7 3000
Also, how would i compute the total hours worked in a 12 hour basis?
Here is my source code:
import java.util.Scanner;
import java.io.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class AYANYAN
{static String ans ;
static int empNumber ;
static String timeIn, timeOut;
static Scanner s = new Scanner(System.in);
static String name[] = { "Ayan Ramirez", "Jenifer Sumbi", "Gen Estrada" , "Tugba Cakir", "Lennox Schatje Huisden"};
public static void main(String args[])throws IOException
{
FileWriter fWriter = new FileWriter("EmpData.txt");
for (int i = 0; i < name.length; i++)
{
fWriter.write(name[i] + "\n");
}
fWriter.close();
start () ;
}
public static void control ()
{
System.out.print ("\n\nPlease select one of the following: \nA. Sign Off\nB. Enter Time in\nC. Enter Time out\nD. Exit Program\n") ;
ans = s.next() ;
if (ans.equalsIgnoreCase("A")){
signOff () ;
} else if (ans.equalsIgnoreCase("B")) {
timeIn () ;
} else if (ans.equalsIgnoreCase("C")) {
timeOut () ;
} else if (ans.equalsIgnoreCase("D")){
System.out.print ("\nBYE!\n\n\nProgram made by: Ayan Ramirez\n") ;
} else {
System.out.print ("ERROR!") ;
System.exit(0);
}
}
public static void start ()
{
System.out.print ("Please enter your id number: ") ;
empNumber = s.nextInt();
if (empNumber == 12345){
System.out.print ("\nSigned in as: " + name[0]);
control() ;
} else if (empNumber == 12346){
System.out.print ("\nSigned in as: " + name[1]);
control() ;
}else if (empNumber == 12347){
System.out.print ("\nSigned in as: " + name[2]);
control() ;
}else if (empNumber == 12348){
System.out.print ("\nSigned in as: " + name[3]);
control() ;
} else if (empNumber == 12349){
System.out.print ("\nSigned in as: " + name[4]);
control() ;
}
else {
System.out.print ("\nNTRUDER ALERT!\n\nPLEASE ENTER THE CORRECT ID NUMBER!") ;
start () ;
}
}
public static void signOff ()
{
System.out.print ("Signing off...\n") ;
start () ;
}
public static String timeIn ()
{
System.out.print ("Please enter time in: ") ;
timeIn = s.next () ;
control () ;
return (timeIn) ;
}
public static String timeOut ()
{
System.out.print ("Please enter time out: ") ;
timeOut = s.next () ;
control () ;
return (timeOut) ;
}
}
The easiest way to produce this kind of output is to use String.format() - its format string syntax supports padding as well as date and time formatting.
With regards to tabbing your information, what exactly do you mean by that?
Do you mean to print a white space which is the same as if you pressed the tab button on your keyboard, or do you mean to allow a program such as excel to be able to display items in colums?
For the first one, if you print something like this: str1 + "\t" + str2, this will cause a white space to be placed between str1 and str2, just as if you pressed the tab key on your keyboard.
If it is the second option, you would nee to enter a delimiter, such as a ; to allow a program such as excel to split them for you, so you will need to do something like this: str1 + ";" + str2.
For the second question, you can take a look at the SimpleDateFormat class. You can do something like so:
K:mm a
This should print the time in AM/PM format.
You can use \t as a tabulation char in Java. A slightly better option is the following: you can just determine the length of the current part of the string by int n = s.length() and append a number of spaces to it to get a fixed string length m. This gives you more freedom on the width than \t, and for varying string length you'd need this anyway.
Sample code:
public String tab(String s, int m) {
int n = s.length();
StringBuffer sb = new StringBuffer();
for (int i=n; i<m; i++) sb.append(" ");
return s+sb.toString();
}
Related
I am just starting and I have created parts of my code, part a finds the int location of the letter(or phrase)that the user is looking for in the Master string(which is line in the code). Part b counts how many times the letter(or phrase appears). In the next part(WITH OUT CREATING A NEW METHOD) I want if s(what the user is looking) is a "_" to replace them with something else like "-" for instance, and then print it out.
here is my code:
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
public class Main
{
//my code acomplishes the goal but it dose not do it the way you are asking for, sorry:(
public static String line; // The line to format
public static void main(String [] arrrgs)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a master String:");
String line = input.nextLine();
System.out.println("Enter a letter to look for:");
String s = input.nextLine();
System.out.println("Enter a starting location:");
int begin = input.nextInt();
//part a
int loc = begin;
while (loc != line.length()){
loc++;
if (loc != line.length()){
if (s.matches(line.substring(loc, loc + 1))){
System.out.println(s + " appears at " + (loc + 1));//prints location of strin except for first one
}
}
}
int oomf = 1;
if(s.matches(line.substring(0, 1)))//looks at first letter
System.out.println(oomf); //prints if nesasary
//part b
int count = 0;
int timer = begin;
while (timer != line.length()){
timer++;
if (timer != line.length()){
if (s.matches(line.substring(timer, timer + 1))){
count++;
}
}
}
System.out.println(s +"apears " + count + " times.");
}
}
As you see from the comments there is JAVA API to manipulate strings.
Here you are an example how to do it.
public static void main(String[] args) {
String testString = "Hello _ World _";
// Replace with Java API:
System.out.println(testString.replace('_', '-'));
// Replace using own naive code:
String newString = "";
for(int i = 0; i < testString.length(); i++) {
if(testString.charAt(i) == '_') {
newString += "-";
} else {
newString += testString.charAt(i);
}
}
System.out.println(newString);
}
You should be able to adopt this to your program.
Please note that in java all strings are immutable. That means, that you can't change an string once it is created. So you have to create new strings with your changes.
This is why you have to work with the return value of replace(). Your original String will remain the same.
I started to study JAVA, So sorry for the question.. I practice the WHILE LOOP, so I have this code:
import java.util.Scanner;
public class Class {
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
double n = 0;
while ( n < 10 )
{
System.out.println( (n+1) + "." + message );
n++;
}
}
}
so, I want to get a result somthing like that: 10. 20. 30. and etc..
but I get: 1.0. , 2.0., 3.0. and etc..
what I should do to remove this dot, between 1 and 0...? thank you very much for your help :).
Use int instead of double for n variable:
int n = 0;
Well, a quick fix to your problem would be first changing the data type to int, so int n = 0; then simply add "0." to your print statement, so it looks like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 10 ) {
System.out.println( (n+1) + "0." + message );
n++;
}
}
}
Or, alternatively, you could do int n = 10 and have your while loop condition aswhile( n < 100 ) then increment n by ten (n+=10;). So now it would look like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 10;
while ( n < 100 ) {
System.out.println(n + "." + message);
n+=10;
}
}
}
you can increment in 10s by multiplying n by 10, Also you might want to use int type rather than double to remove the decimal point.
int n = 1;
while ( n <= 10 )
{
System.out.println( ( 10 * n) "." + message );
n++;
}
You can try something like this:
int n = 10; // start from 10 and change it from double to int to get rid of decimal point
while ( n <= 100 ){
System.out.println( n + "." + "message");
n+=10; // increment by 10 after every loop
}
I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.
I just want to calculate your future age. You enter 3 things: your current age, the current year, and the future year. I was experiementing with for and do while loops. Then I came cross this problem, variable currentAge is not initialized. But none of the other variables are initialized either, other variables are fine. The only difference here is others are in the do while loop, but currentAge is in the for loop. Why did this happen? Can somebody explain the difference and why? Please see the below code.
import java.util.Scanner;
public class Lab3Class
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String cleanUpStr;
int currentAge;
int futureAge;
int currentYear;
int futureYear;
for (int cntr = 0; cntr < 3; ++cntr)
{
System.out.print("Enter your current age\t");
currentAge = input.nextInt( );
cleanUpStr = input.nextLine( );
}
if (currentAge >= 0){
do
{
System.out.print("Enter current year\t");
currentYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(currentYear < 0);
do
{
System.out.print("Enter future year\t");
futureYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(futureYear < 0 || futureYear < currentYear);
input.close();
futureAge = currentAge + (futureYear - currentYear);
System.out.println("In the year " + currentYear + " you are " + currentAge + " years old");
System.out.println("In the year " + futureYear + " you will be " + futureAge + " years old");
} else {
System.out.println("Too many tries for an valid age!");
}
}
}
The do / while loop code block is executed once (at least) no matter what the condition is. But the for loop does not follow the same tradition : The for loop checks whether the condition is valid FIRST, THEN it executes.
Execution DEMO:
For loop : (pre; condition; post)
Check the condition -> If condition is true -> 2. Execute code block -> 3. Go on to next iteration
Do / While loop: do { }while(condition);
Execute code block -> 2. Check condition -> If condition is true -> 3. Go on to next iteration.
Try this version of code it's perfect:
import java.util.Scanner;
public class Lab3Class {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String cleanUpStr;
int currentAge = 0;
int futureAge;
int currentYear;
int futureYear;
System.out.print("Enter current age\t");
currentAge = input.nextInt();
if (currentAge >= 0) {
do {
System.out.print("Enter current year\t");
currentYear = input.nextInt();
cleanUpStr = input.nextLine();
} while (currentYear < 0);
do {
System.out.print("Enter future year\t");
futureYear = input.nextInt();
cleanUpStr = input.nextLine();
} while (futureYear < 0 || futureYear < currentYear);
input.close();
futureAge = currentAge + (futureYear - currentYear);
System.out.println("In the year " + currentYear + " you are "
+ currentAge + " years old");
System.out.println("In the year " + futureYear + " you will be "
+ futureAge + " years old");
} else {
System.out.println("Too many tries for an valid age!");
}
}
}
In order to make it works - you just need to change currentAge declaration line setting it to initial value, like this:
int currentAge = 0;
Java initialize class fields with default values, but not methods variables.
As an alternative solution (just to improve understanding) I would recommend to move declaration of currentAge to class level and leave it without default value, like following:
public class Lab3Class
{
private static int currentAge;
...
}
The program behavior will be the same, but will depict difference between field and method variable declaration and initialization.
You may find useful following links:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.1
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5
This question already has answers here:
Error: 'else' without 'if' [closed]
(3 answers)
Closed 7 years ago.
At line 53 it is giving me an error of else without if. I clearly have an if statement, but i don't know what i'm doing wrong to make java not recognize it. I've tried moving around the braces and nothing is working.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Quiz6
{
public static void displayInfo()
{
System.out.println(
"\n\tAuthor: Allen Watson \n" +
"\tClass: \tCSCI 1250-001 \n" +
"\tDate: \t10/09/2013 \n" +
"\tLab: \tQuiz6 \n");
}
public static double calculatePay(int hourWorked, double hourlyRate)
{
double dPay;
dPay = (hourWorked * hourlyRate);
return dPay;
}
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
DecimalFormat dfMoney = new DecimalFormat("$#,##0.00");
String strName;
int iCount;
int iDaysWorked;
int iTotalHoursWorked;
int iSingleDayHours;
double dHourlyRate;
final byte WEEK = 7;
displayInfo();
System.out.print("\tWhat is your name: ");
strName = Keyboard.nextLine();
System.out.print("\n\tHow many days did you work this week: ");
iDaysWorked = Keyboard.nextByte();
System.out.print("\n\tHow much do you make an hour: ");
dHourlyRate = Keyboard.nextDouble();
if(dDaysWorked <= WEEK);
{
for(iCount = 1; iCount <= iDaysWorked ; iCount++)
{
System.out.print("\tHow many hours did you work on the day"+iCount+":");
iSingleDayHours = Keyboard.nextInt();
iSingleDayHours += iTotalHoursWorked;
}
}
else
{
bDaysWorked = 0;
System.out.print("A week can only have seven days");
}
calculatePay(iTotalHoursWorked,dHourlyRate);
System.out.print("Hello "+strName+", you worked a total of "+iTotalHoursWorked+" hours over "+iDaysWorked+" days.");
System.out.print("\nWith am hourly rate of "+dfMoney(dHourlyRate)+" you made "+dfMoney(dPay)+".");
}
}
Here's the problem:
if(dDaysWorked <= WEEK); // remove the ;
That trailing ; is making Java believe that the if statement is finished, and the {} block after it is outside the if condition, consequently the else part has no matching if preceding it.
This is a rather frequent bug, and a hard one to spot. If it weren't for the else block, the code would have compiled correctly, but it would have been wrong. Bottom line: never, ever put a ; in the opening line of an if, for or while statement.
if(dDaysWorked <= WEEK); - remove last ;