Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need help to fix my code. I don't know where is the problem, but it seems in printf the compiler give me error when I run this code. Why?
Employee emp1 = new Employee();
emp1.setFname("Kim");
emp1.setLname("Yee");
emp1.setID(101);
emp1.setSalary(40000);
Employee emp2 = new Employee();
emp2.setFname("Lana");
emp2.setLname("Yum");
emp2.setID(102);
emp2.setSalary(55.000);
Employee emp3 = new Employee();
emp3.setFname("Alex");
emp3.setLname("Jhone");
emp3.setID(103);
emp3.setSalary(55.500);
Employee emp4 = new Employee();
emp4.setFname("joe");
emp4.setLname("mac");
emp4.setID(104);
emp4.setSalary(74.000);
System.out.println("Employee Name \t Employee ID \t Employee salary");
System.out.printf("%s %s\t%d\t$%f\n", emp1.getFname() + "" + emp1.getLname(), emp1.getID(), emp1.getSalary());
System.out.printf("%s %s\t%d\t$%f\n", emp2.getFname() + "" + emp2.getLname(), emp2.getID(), emp2.getSalary());
System.out.printf("%s %s\t%d\t$%f\n", emp3.getFname() + "" + emp3.getLname(), emp3.getID(), emp3.getSalary());
System.out.printf("%s %s\t%d\t$%f\n", emp4.getFname() + "" + emp4.getLname(), emp4.getID(), emp4.getSalary());
#Nishant Shreshth and #hexafraction are right. However, you have not thought the problem through. Any time you have repetitious code like this, you're missing an opportunity. Why not write a method on Employee to return the full name of the employee? You will certainly find more places to use that in a real program.
public String getFullName() {
return fname + " " + lname;
}
One should avoid drudgery. Remember Larry Wall's three virtues of programming: hubris, impatience, and laziness. You should do extra work now so you can be lazy later.
Now, a person's first and last names are more associated with each other than with his id and salary. Also, people have names even if they aren't employees. So, you should really create a Name class and use it in Employee (or Person, or Student, or Customer...) instead of fname and lname. You can then make changes to it when requirements change. How difficult would it be to add middleInitial to all the classes that keep name components? What of title? What of suffix? You may not have the requirement to do that now, but it's a matter of judgement how much to prepare for the future.
If you become a Java programmer, you may also want to have your class implement java.util.Formattable. That is an advanced topic.
System.out.printf("%s %s\t%d\t$%f\n", emp1.getFname()+""+emp1.getLname(), emp1.getID(),emp1.getSalary());
This is the culprit:
emp1.getFname()+""+emp1.getLname()
That expression right above is ONE string. Use:
System.out.printf("%s\t%d\t$%f\n", emp1.getFname()+""+emp1.getLname(), emp1.getID(),emp1.getSalary());
or
System.out.printf("%s %s\t%d\t$%f\n", emp1.getFname(), emp1.getLname(), emp1.getID(),emp1.getSalary());
so you have a matching number of parameters and format specifiers in the format string.
I think +""+ should be just a ,
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
There are Two Strings s1 and s2, then split them and add them with one another.
Please find below snippet for more information,
Input :-
String s1 ="Sheldon Cooper";
String s2 ="Howard Wolowitz";
Output :-
Sheldon Wolowitz
Howard Cooper
Can anyone help me on this....
you can use Split String method in java
String[] arrOfS1 = s1.split(" ");
String[] arrOfS2 = s2.split(" ");
System.out.println(arrOfS1[0] + " " + arrOfS2[1]);
System.out.println(arrOfS2[0] + " " + arrOfS1[1]);
I am tasked with creating a simple Turing Test using ArrayLists. I know how to create the ArrayLists, but I'm having trouble connecting them to the if statements to respond properly to the user input. An example of this issue is below. When the user inputs Frank I want the first response, and any other input should result in the other response. However, whatever tweaks I make just make one or the other show up no matter what I input.
List<String> names = new ArrayList<>();
names.add( "Frank" );
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if( names.contains( "Frank" )) {
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}
else {
System.out.printf( "What an interesting name. My name is John.\n");
}
**Having another issue. For the second question I'm trying to use an else if statement. However, when I respond with the else if response, it gives me the final else response of "I would have never guessed" every time.
System.out.print("Where are you from? ");
states.add(scanner.next());
if (states.contains("Florida") || states.contains("florida")) {
System.out.println("So was I!\n");
} else {
if (states.contains("North Carolina") || states.contains("north carolina")) {
System.out.println("I hear that's a nice place to live.\n");
}
else {
System.out.println("I would have never guessed!");
}
}
Try the following:
List<String> names = new ArrayList<>();
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if(names.contains( "Frank" )){
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}else{
System.out.printf( "What an interesting name. My name is John.\n");
}
I removed the part where you add Frank to the array. This way the results might be a little different depending on your input. I still find it a little strange that you are using an ArrayList. It seems like just saving a simple variable could do the same thing.
With an ArrayList it is possible however that you could have previous answers affect other answers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've created this Array which holds Basic Salary
static String[] BASICSALARY = {"$8096","$7661","$2427","$8467","$9122"," "," "," "};
And I'm willing to calculate the Total Salary in a method and then print the Total Salary Beside the Basic.
private static void CalTotalSalary()
{
System.out.println(" ID\tEmployee Name\t\t Years of Expirence\tBasic Salary\t\tTotal Salary");
int size = ID.length;
for (int i=0; i<size; i++)
{
System.out.println(" " + ID[i] + " " + FN[i] + " " + LN[i] + "\t\t " +
YEARSOFEXP[i] + "\t\t" +BASICSALARY[i] );
}
}
I have thought of simply making an Array and enter the values manually, But in fact, I need to do the Calculation inside the program. Otherwise this's not programming.
Any Suggestions?
First of all I recommend you to use List instead of plain Array. Its more flexibel and useful.
get your basicsalary into a List.
Use List<String> operators =LISTENTRY.split("[0-9]+"); for each entry in your list. Parse them. Then add them together. Simple as that.
I dont want to post plain code, it doesnt help you learn. Just watch some basic List tutorials or read a beginners Javabook to get into it.
Greetings, David
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a new user and I have a "noob" question. We are being taught Java in school and I have a question about one of our activities. One requirement is to take in student info (such as course) and convert them to a single letter (I assume use .charAt??) and then later on count how many students are enrolled into that course. I have the student info down here:
import java.util.*;
import java.lang.*;
public class CourseTallier
{
public static void main (String[] args)
{
String student = inputStudInfo();
}
public static String inputStudInfo ()
{
Scanner kbd = new Scanner(System.in);
int limit = 0, idnum = 0;
String college = "";
System.out.println("Please input a valid ID number:");
idnum = Integer.parseInt(kbd.nextLine());
if (idnum == 0)
{
System.out.println("Thank you for using this program.");
System.exit(0);
}
while (idnum < limit) {
System.out.println("Invalid ID number. Please enter a positive integer:");
idnum = Integer.parseInt(kbd.nextLine());
}
System.out.println("Please enter a valid course (BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
while(!college.equalsIgnoreCase("BLIS") && !college.equalsIgnoreCase("BSCS") && !college.equalsIgnoreCase("BSIS") && !college.equalsIgnoreCase("BSIT"))
{
System.out.println("Invalid course. Please enter either BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
}
return college;
}
public static Character convertCourse (String college)
{
}
and as you can see I am stuck at the "Convert Course" method (modular is required). I was wondering how would I convert something like "BLIS" to a single character "L" and then create another method that counts the number of how many students are enrolled in that course.
I am not asking for someone to complete this program for me cause that would be cheating. I am simply asking someone for a shove in the right direction. Your help is very much appreciated.
Edit: As asked here are the exact requirements:
Program
To the storing for future values, do you know what instance variables are? Unless I misunderstood the question, it seems like it would make sense to make four (static) instance variables that hold the count of users enrolled in each course.
You could either use the .charAt method or use the "switch" statement.
the problem with the charAt method is that you probably can't find different letters for each course using the same indexed letter.(which will bring you to the switch statement again)
To count the number of student enrolled in that course you should have a count variable and increase it every time you convert a course into a single char.
One way would be to use a switch statement
switch(college)
{
case "BLIS":
return("a");
}
Not sure if thats really what your meant to be doing, if your meant to store student data then a Map implementing datastructure would be the go
Well, first of all you need to make your code more modular. How about dividing it into sections,like, getting user input, validating user input, storing user input.
Well to store the user data, you can use something like a HashMap. Keep course as key (eg BLIS) and no of students as value. In start intialize it with 0.
Map<String, Integer> studentCourseHashMap = new HashMap<String, Integer>();
studentCourseHashMap.put("BLIS", 0);
So, every time a user enrolls for the particular course all you need to do is to find the course and increment it by 1. So, for example if a student enrolled for BLIS course. then,
if(studentCourseHashMap.containsKey("BLIS")){
//Checking if BLIS course is available
Integer noOfStudents = studentCourseHashMap.get("BLIS");
//Increment no of students for each enrollment
noOfStudents++;
//Saving the updated value in hashmap
studentCourseHashMap.put("BLIS", noOfStudents);
}
Hope this will help, mention your doubts in comments. :)
why not use a counter for each course and increment it whenever the user enters it.
switch(college)
case BLIS:
blisCounter+=1;
break;
case BSCS:
bscsCounter+=1;
break;
case BSIS:
bsisCounter+=1;
break;
case BSIT:
bsitCounter+=1;
break;
If you want to take each letter from the string, here's the way:
String str = "BLIS";
String strArray[] = str.split("");
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}
If you want to map the Course String to individual Characters, below is the way:
Map<String, Character> courseMap = new HashMap<String, Character>();
courseMap.put("BLIS", 'L');
courseMap.put("BSCS", 'C');
courseMap.put("BSIS", 'S');
courseMap.put("BSIT", 'T');
for(String courseStr: courseMap.keySet()) {
System.out.println(courseStr + " > " + courseMap.get(courseStr));
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Like topic says I'm looking for the best way to:
I got .txt file. In this file there are for example:
Matthew Sawicki 25\n
Wladimir Putingo 28\n
Barracko Obamaso 27
Whats the best way to write a program that opens this file, checks out the biggest number and then prints out that?
I was thinking about: open file -> check each line with hasNextLine method saving the biggest number (addin i for measuring the lines - 1, 2, 3) and then close file and open again and then somehow prints out that line
Ok there goes edit then.
By the way I have to write name of file in console to open it. And I have to use Scanner.
My code:
Scanner scanner= new Scanner (System.in);
File file = new File (scanner.nextLine);
scanner = new Scanner (file);
int temp=O;
int i=0;
while (scanner.hasNextLine) {
String word1=scanner.next;
String word2=scanner.next;
String word3=scanner.next;
If(word3>temp)
temp3=word;
i++; // now i get the i id of the line with the biggest number
And now I'm thinking bout reopen file and loop again to print out that line with the biggest number(By for instance if(newWord3==temp))
is it a good idea? And how to reopen the file? can anyone continue the code?
Assuming that this file will always be in the same format here's a snippet that does what you want with no checking to make sure that anything is in the wrong place/format.
//Create a new scanner pointed at the file in question
Scanner scanner= new Scanner(new File ("C:\\Path\\To\\something.txt"));
//Create a placeholder for the currently known biggest integer
int biggest = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
//This line assumes that the third word separated by spaces is an
// integer and copies it to the `cndt` variable
int cndt = Integer.parseInt(s.split(" ")[2]);
//If cndt is bigger than the biggest recorded integer so far then
// copy that as the new biggest integer
biggest = cndt > biggest ? cndt : biggest;
}
//Voila
System.out.println("Biggest: " + biggest);
You'll want to verify that the number in question is there, and that you can handle the case that a line in your text file is malformed
There are several ways to do what you want. The way you described can work, but as you noted it requires to scan the file twice (in the worst case, which is when the row you have to print is the last one).
A better way which avoid to reopen the file again is to modify your algorithm to save not only the biggest number and the corresponding row number, but saving the whole line if the number is bigger than the one previously saved. Then, when you're done scanning the file you can just print the string you saved, which is the one containing the biggest number.
Note that your code will not work: the if is comparing a String with an int, and also there's no temp3 variable (that's probably just a typo).
To follow my suggestion you should have something like this:
int rowNumber = Integer.parseInt(word3);
if(rowNumber > temp) {
temp = rowNumber;
tempRow = word1 + " " + word2 + " " + word3;
}
then you can just print out tempRow (which you should define outside the while loop).
It's all fine now. I've made a simple mistake in my file (an empty enter at the end) so i coudnt figure out how to do it.
Thanks for ur effort and gl!.