Symbol table in Java - java

I'm trying to write a program for manipulating a symbol table in Java. I've used a linked list data structure as a way to represent my symbol table; the linked list(singly) has a key,value associated to that key, and a pointer to the next point. The linked list also provides to the user the function of inserting a new node to the list. It seems that my implementation for the linked list class is going well, but when I was trying write a main program to test that, I've got some problems. Despite the errors that I managed somehow to handle them with exceptions, there is a logical error in my code. Here is the piece of code that I wrote and the output as well:
import java.util.Scanner;
public class Test_GPA {
public static void main(String[]args){
// create symbol table of grades and values
GPA<String, Double> grades = new GPA<String, Double>();
grades.put("A", 4.00);
grades.put("B", 3.00);
grades.put("C", 2.00);
grades.put("D", 1.00);
grades.put("F", 0.00);
grades.put("A+", 4.33);
grades.put("B+", 3.33);
grades.put("C+", 2.33);
grades.put("A-", 3.67);
grades.put("B-", 2.67);
Scanner input = new Scanner(System.in);
double numb =0; int i=0;
double sum = 0.0;
String grade;
Double value;
System.out.println("Please enter number of courses:");
numb=input.nextInt();
while(i<numb){
System.out.println("Please enter the grade for course"+(i+1)+":");
grade = input.nextLine();
value = grades.get(grade);
try{
sum += Double.valueOf(value);
}catch(Exception e){}
i++;
}
double gpa = sum/numb;
System.out.println("GPA = "+gpa);
The problem is the code always skips the reading of the first entry by the user. For example, if I run this program and enter the number of courses to be 4, the result will be as shown:
Please enter number of courses:
4
Please enter the grade for course1:
Please enter the grade for course2:
A
Please enter the grade for course3:
A
Please enter the grade for course4:
A
GPA = 3.0
I don't know actually where is the mistake that I've made. And of course by missing the reading of the first entry that leads to a wrong computation for the GPA. Please, is there anyone interested in showing me how to fix the error. I've tried almost everything i know and it still doesn't work. just FYI, this is the first time i program in Java. Thank you in advance.

Firstly your implementation of LinkedList is not correct linkedlist is not a key-value type of data structure it just links element to other element. I recommend you to look into HashTable that is better for this kind of usage. What happens in your code is new-line character does not get consumed when you get input with nextInt(). Below code should do the trick
numb = Integer.parseInt(input.nextLine());

Related

How to make scanner scan multiple inputs from one scanner line in java?

The user should be able to input data of 5 customers with balances. However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.
import java.util.Scanner;
public class Assignment {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
Customer c [] = new Customer [5];
Customer hold;
String name; int count = 0;
double totalBalance = 0.0;
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
System.out.println("Search for all customers who have more than $100");
for (int i=0; i<count ; i++){
if (c[i].getBalance()>100)
System.out.println(c[i].getName());
totalBalance += balance;
averageBalance = totalBalance/5;
System.out.println("The average balance is: "+averageBalance);
}
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
}
So, in the above code the display message prints 5 times but every time it will be for different customers. For e.g.
Enter 1 customer name and balance
John
20.0
Enter 2 customer name and balance
Jim
10.0
and so on.
I hope this helps. If you ask me you should be using java.util.ArrayList or java.util.LinkedList. These classes come with many features out of the box and you need not code much as in the case of arrays.
You are asking is not a coding problem but just a matter of design.
For what you are doing as per design you can follow below process or similar.
Enter comma separated user names in single line.
Read the line and split the names, now you have x customers detail like name read in a single shot.
Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, i.e. one, line one detail like salary of emp or department.
for pseudo code:
private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function
// using readed line/console input, split it on comma using split() function and return array of values.
}

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

How to store a value for later use? [closed]

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));
}

Validating the kind of data in an ArrayList java

Hello everyone~ I'm a little new in this theme of programming. I'm here to expose a particular case, of my college project, hoping that can find a way to validate the java code.
Basically, I'm designing a system to sum the daily sales of a company and save them into a matrix. The code below corresponds to the first day only.
package fsystem;
import java.util.ArrayList;
import java.util.Scanner;
public class class_Sist {
public class_Sist() {
}
ArrayList <Integer> MondayPrices = new ArrayList();
int Week[][]= new int [2][7];
public void addPricesDay1(){
Scanner scn = new Scanner(System.in);
String answer;
Integer auxAddition=0;
boolean flagNext= false, flagAgain= false;
System.out.println("Next it is come to apply the amounts of sales made on the day "+Week[0][0]+". Please "
+ "indicate the price of each of the items that were sold.");
do {
System.out.println("Enter the price of the corresponding article.");
MondayPrices.add(scn.nextInt());
do {
System.out.println("It requires enter the price of another article?");
answer= scn.next();
if (("Yes".equals(answer))||("yes".equals(answer))) {
flagNext=false;
flagAgain=true;
}
if (("No".equals(answer))||("no".equals(answer))){
flagNext=false;
flagAgain=false;
System.out.println("Introduced sales prices have been stored successfully.");
}
if ((!"Yes".equals(answer))&&(!"yes".equals(answer))&&(!"No".equals(answer))&&(!"no".equals(answer))) {
System.out.println("Error. Please respond using by answer only yes or no.");
flagNext=true;
}
} while (flagNext==true);
} while (flagAgain==true);
for (int i=0; i<MondayPrices.size(); i++) {
auxAddition= auxAddition+MondayPrices.get(i);
}
System.out.println("The total amount in sales for monday is "+auxAddition);
Week[1][0]=auxAddition;
}
}
So, what I need is to validate that the data inputted by the user be only numeric, and never otherwise, but I don't know completely how ArrayList works, therefore, I would greatly appreciate if someone could explain me how I can do that.
Use Scanner hasNextInt() function.
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method.The scanner does not advance past any input.
Use it with while to check whether the input is integer.
Scanner stdin = new Scanner(System.in);
while (!stdin.hasNextInt()) stdin.next();
MondayPrice.add(stdin.nextInt());
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29
You can validate the input before adding the integer in the ArrayList.
I hope this will help - How to use Scanner to accept only valid int as input

Array setting length and storing information

This is homework. I'm trying to work with arrays and this is the first project working with them. My book shows all kinds of examples but the way they code the examples doesn't do any justice to what the assignment calls for.
I am trying to write a program that asks a user to enter students into the system. The program first asks how many you will enter then it will prompt you for the first name, last name, and score.
What I am trying to accomplish with this section of code is to ask the user how many students they will enter. The line of code that says
getStudentCount();
is a method that collects that information and then returns studentCount
I tried to code this to where the length of the array is going to be the number the user enters but it's not working so I wanted to ask for guidance. Ideally if this works and the user enters 3 then you will be prompted to enter the information 3 times. If the user enters 0 then the program doesn't ask you anything.
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application.");
int studentCount = 1;
getStudentCount();
studentCount = sc.nextInt();
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
{
Student s = new Student();
String firstName = getString("Enter first name: ");
s.setFirstName(firstName);
String lastName = getString("Enter last name: ");
s.setLastName(lastName);
int score = getScore("Enter score: ");
s.setScore(score);
}
}
Everything I had in the program worked up until I tried to code
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
which tells me there is something wrong with the way I am doing this.
Also the assignment asks that I store the information in the array. I'm not clear on how to call it or I guess store it.... I have another class with setters and getters. Is that enough to store it? How would I call it?
Again this is homework so any guidance is appreciated.
Thanks!
Well that's at least a homework example that shows some work on the part of the askee (and nicely written), so here's some help:
You set the studentCount to 1 and then call getStudentcount(), but never assigns the return value to your variable, hence the variable stays 1 (though you're overwriting it afterwards with sc.nextInt() which is probably not what you want if you already have a nice method for it). The fix is just to assign the return value of your method to the variable [1]
[1] Yes I know I shouldn't answer homework questions completely, but I really saw no way whatsoever to answer that only partially - proposals welcome though :)
My hints:
Look carefully at how you are getting the student count, and where you are putting it. You seem to be getting the count in two different ways, and that is at best redundant, and probably a bug.
Presumably there is a stack trace. Read it!!
The stack trace will tell you what exception was thrown, what its diagnostic message is, where it was thrown, and where in your code it was executing when the problem happened.
If you are having difficulty visualizing what is going on, use your Java IDE's debugger and single step the program.
Based on your follow-up comments, there isn't a stack trace. But if there was one, you should read it :-)
I don't understand your lines
getStudentCount();
studentCount = sc.nextInt();
if getStudentCount() "returns" the number they input (as you describe in your text), seems like you should be doing
int studentCOunt = getStudentCount();
I'm trying not to completely do your homework for you, but take a look at the code below for a glimpse of how to do this:
/* Some Declarations You're Going to Need */
private static Scanner scan = new Scanner(System.in); //Private, only need it in here
public static Student[] students; //Public, access it from any class you may need
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
System.out.print("Amount of students:");
int studentCount = scan.nextInt();
students = new Student[studentCount];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
System.out.print("Enter first name:");
String firstName = scan.next();
students[i].setFirstName(firstName);
System.out.print("Enter last name:");
String lastName = scan.next();
students[i].setLastName(lastName);
System.out.print("Enter score:");
int score = scan.nextInt();
students[i].setScore(score);
}
scan = null; //Done with scanner
}

Categories