Is there no such thing as hasNextChar?

I'm trying to make a program to figure out a grade point average, and a solution I've come up with to deal with the +/- is to assign it as a char and give it a value from there, but I run into problems when there is no char after the letter grade. I thought a hasNextChar would take care of this problem, since it would only assign a value if the +/- was present, but from what I can tell, hasNextChar doesn't exist in Java?

I'm not sure that I understand your problem. If you represent the grades as String then if the length is more than 1, you have a sign afterwards, otherwise you don't. You can represent the grades using enum as well.

Sorry I must not have explained it well, I'm reading from a data file that will have data like this:

A- 4
B+ 3
C 3
D+ 3

I read the A-, B+, C, and D+ as a string, create a variable to assign a char value using charAt(0), that holds the letter, which is then put into a switch statement which tells what value the letter grade is (1.0,2.0,3.0,4.0). I would like to read the charAt(1) of the string, and if it is a +, add .3 to the value, and if it is -, minus .3 from the value. That's fine, it just causes a problem when there isn't a character at charAt(1) to read.

You can have either '-', '+' or whitespace, and you can compare all three cases. When you read the line check that the entire length is more than 1 - if not then you don't even have a number afterwards, and you should (probably) ignore the line.

Ok I understand what you're saying. I see that it would work, comparing all three cases. I'm just not getting the right results when I run the program now, -_- . Logic error I'm sure.

Well, right now I am off to bed, but if you still can't get your code to work post it here and I'll try and give it a look tomorrow. Good luck!

Thanks, I'll keep that it mind. I'll just stare at it for a while and hopefully figure out what's up. Otherwise the code may be here. Haha.

OK, is each string line format always that way? I mean grade which may or may not followed by a sign(+/-), and then a number? If so, what you need is to read in as a line string. Then use split() to split the string using white space as delimiter which should produce an array size 2. The first subscribe is your grade and the second is the credit. Now, if the grade is size of 2, you already know that it contains a sign. Read each character using charAt(). Compare the returned char to get what grade and what sign it is...

The String class detail can be found here.

Edited 6 Years Ago by Taywin: n/a

There are a few ways you can approach this.

1. Simply put a try-catch around the part where you get charAt(1)
2. Place some sort of symbol after each letter, like "!". Since you're probably using an if-statement anyways for + and -, it'll take in the char and just ignore it.

@coil,

I am sorry but I disagree with both of your approaches.
1.It is not a good practice to rely on Exception even though there are a few cases that you may want to. In this case, it is not necessary at all.
2.Adding more letter is similar to adding more complexity. If the string is the way it is, why would you want to increase the complexity of the work?

Assuming that each line consists of <Grade><one whitespace><Number> Then when charAt(0) is the letter, charAt(1) is the sign. If you are getting the grade separately and the number separately, then (grade.length() > 1) should tell you if there is a sign or not.

Handling it through exception unless it is absolutely necessary is bad coding in my opinion.

Hasn't anyone thought of using the split method:

String s = "A- 4";
String [] tok = s.split(" ");

// tok[0]: A-
// tok[1]: 4

If you have "B 4" then again you will get an array of two elements.
Then check the length of tok[0]. If it is one then it has only the letter:
tok[0].charAt(0)

If it has length 2 then it also has a +/- :
tok[0] = "A-"
tok[0].charAt(0)
tok[0].charAt(1)


EDIT:
Or even the index of method:

String s = "A 4";
int index = s.indexOf(" ");
String letter = s.subString(0, index); // it might have A+ if the initial string has the symbol +/-
String number = s.subString(index+1, s.length);

Edited 6 Years Ago by javaAddict: n/a

@javaAddict
I stated the approach in my answer.

@apines
That's why my approach checks for the string length instead of immediately access the string at the position.

Edited 6 Years Ago by Taywin: n/a

@javaAddict
I stated the approach in my answer.

@apines
That's why my approach checks for the string length instead of immediately access the string at the position.

Ok. I didn't see it in so many posts. I assumed that If someone had given such suggestion it wouldn't be necessary for more posts after yours

javaAddict: It is not a problem. I just want to point it out. :)

apines:

This is not an intension to make an argument, but I want to be clear about your approach. Using try-catch when it is not necessary is not a good practice. One should not rely on exception thrown. The reason is why would you expect your code to throw exception at the first place? If it happens and you know the cause, redesign the way you handle the job. The only think you would expect to throw exception is when it is out of your control. In this case for OP, he/she has the total control of the job.

Taywin - I have stated that using a try/catch in this way is bad coding, so why do you think that I support it?

Wow this thread really took off when I was gone. Just to be clear, the format for the file data will always look like this:

A 3
B+ 2
C- 4
W 0

Or some variation. My problem is that coursePoints is always displayed as 0.0 in my output. I need to find that problem first before I move onto finding complete GPA. I think the way it's set up now will work and hopefully the problem is small.

import java.io.*;
import java.util.Scanner;
public class HW8
{
     public static void main (String[] args) throws IOException
      {
        System.out.print("Jacob Julian\nCPS180\nLast Revised 10-27-10\n\n"); 
      
        Scanner keyboard = new Scanner(System.in);

        System.out.println("What is the name of the file?");
        String fileName = keyboard.nextLine();
        System.out.println(" ");
    
        File file = new File(fileName);
        Scanner inputFile = new Scanner(file);
     
        int totalCredits=0;
        while (inputFile.hasNext())
        {
            double coursePoints=0;
            //Reads the file and seperates the grade and credits portion.
            String grade = inputFile.next();
            int credits=inputFile.nextInt();
            char plusMinus=' ';
           
            System.out.println(grade+"\t"+credits);
            
            //This line should use the coursePoints variable from the method below and display it.
            coursePoints(grade,credits, plusMinus);
            System.out.println("Course points ="+coursePoints);
            System.out.println("");
            
            
            totalCredits=totalCredits+credits;
        }
        System.out.println(" ");
        System.out.println("Total Credits:"+totalCredits);
    }
    
    /**This method should take the letter grade from the data file and assign it a value named
    * gradePoints. If the second character in string 'grade' is a + or -, the appropriate
    * action should be taken to modify the gradePoints variable.It should then take the gradePoints 
    * and multiply them by the credits for each class, which is read in the main method.
    * The result is the coursePoints, and that is to be returned to the main method and displayed.
    */
    public static double coursePoints (String grade,int credits, char plusMinus)
    {
       double gradePoints=0.0;
       char gradeLetter=grade.charAt(0);
       
       //Asssigns point values for letter grades
        switch (gradeLetter)
        {
        case 'a': 
        case 'A':gradePoints=4.0;
            break;
        case 'b':
        case 'B':gradePoints=3.0;
            break;
        case 'c':
        case 'C':gradePoints=2.0;
            break;
        case 'd':
        case 'D':gradePoints=1.0;
            break;
        case 'e':
        case 'E':gradePoints=0.0;
            break;
        }
        
        //If there is a '+', add .3 to gradePoint, if '-', subtract .3.
        if (plusMinus=='+')
        {
            gradePoints+=.3;
        }
            else if (plusMinus=='-')
            {
                gradePoints-=.3;
            }
            else if (plusMinus== ' ')
                gradePoints=gradePoints;
       double coursePoints=gradePoints*credits;
       
       //To return the coursePoints variable
        return coursePoints;
    }
}

On line 25, you declare plusMinus and gives it an white space. Then you pass it into your coursePoints method. What's the point for it??? Also, the way you obtain the grade is a better way, but yet the grade would also contain + or - already. If you pass it in that way, the A- will not be matched with your switch. As a result, your default value (initialized value for gradePoints) is used (0). That's why it returns a 0 for you.

To fix this, you may get rid of variable plusMinus in your main, and also remove it from function argument. Then inside coursePoints, declare a variable (call it plusMinus if you want). Now, check the length of your 'grade' variable using length() method. If the length is 2, you have a sign in your grade; otherwise, its length should be 1 (contain only a grade). If its length is 2, the plusMinus variable will be equal to the string at charAt(1). Then, the grade should be substring(0,1) of the original grade string. After that, you can keep all you are doing right now in your program.

Ok, I see what you're saying here. I moved the plusMinus variable from main into the coursePoints method, I had to initialize it to use it in the if loop later. I found the length of the string grade, and from what I see, it should work, but still returns 0.0. Just out of curiosity, I changed the default value for gradePoints, but it still came back as 0.0. Here is the code I added, right at the beginning of coursePoints.

int strLength=grade.length();
       char plusMinus=' ';
       if (strLength==2)
         plusMinus=grade.charAt(1);
// this must happen before you check for grade.
       int strLength=grade.length();
       char plusMinus=' ';
       if (strLength==2) {
         plusMinus=grade.charAt(1);
         // also replace the string of grade with the chart at 0 here as well
         // because the grade string is still with sign
       }

Edited 6 Years Ago by Taywin: n/a

I'm sorry, I still can't get this. I moved the block of code in front of where I check for the letter grade and I still get the same results. This is really annoying, especially since I know it's something small. Here is ALL my code, and I can't see why this isn't working.

import java.io.*;
import java.util.Scanner;
public class HW8
{
     public static void main (String[] args) throws IOException
      {
      
        Scanner keyboard = new Scanner(System.in);

        System.out.println("What is the name of the file?");
        String fileName = keyboard.nextLine();  
        System.out.println(" ");
    
        File file = new File(fileName);
        Scanner inputFile = new Scanner(file);
     
        int totalCredits=0;
        while (inputFile.hasNext())
        {
            double coursePoints=0;
            //Reads the file and seperates the grade and credits portion.
            String grade = inputFile.next();

            int credits=inputFile.nextInt();          
            System.out.println(grade+"\t"+credits);
            
            //This line should use the coursePoints variable from the method below and display it.
            coursePoints(grade,credits);
            System.out.println("Course points ="+coursePoints);
            System.out.println("");
            
            
            totalCredits=totalCredits+credits;
        }
        System.out.println(" ");
        System.out.println("Total Credits:"+totalCredits);
    }
    
    /**This method should take the letter grade from the data file and assign it a value named
    * gradePoints. If the second character in string 'grade' is a + or -, the appropriate
    * action should be taken to modify the gradePoints variable.It should then take the gradePoints 
    * and multiply them by the credits for each class, which is read in the main method.
    * The result is the coursePoints, and that is to be returned to the main method and displayed.
    */
    public static double coursePoints (String grade,int credits)
    {
       double gradePoints=0.0;
       
       int strLength=grade.length();
       char plusMinus=' ';
       if (strLength==2)
           plusMinus=grade.charAt(1);
           
       char gradeLetter=grade.charAt(0);
       //Asssigns point values for letter grades
        switch (gradeLetter)
        {
        case 'a': 
        case 'A':gradePoints=4.0;
            break;
        case 'b':
        case 'B':gradePoints=3.0;
            break;
        case 'c':
        case 'C':gradePoints=2.0;
            break;
        case 'd':
        case 'D':gradePoints=1.0;
            break;
        case 'e':
        case 'E':gradePoints=0.0;
            break;
        }
    
        
        //If there is a '+', add .3 to gradePoint, if '-', subtract .3.
        if (plusMinus=='+')
        {
            gradePoints+=.3;
        }
            else if (plusMinus=='-')
            {
                gradePoints-=.3;
            }
            else if (plusMinus== ' ')
                gradePoints=gradePoints;
       double coursePoints=gradePoints*credits;
       
       //To return the coursePoints variable
        return coursePoints;
    }
}

The method course points returns a double as a result, but inside your main method you are not assigning is to the variable (line 28), so the variable is not changed. Try this:

//This line should use the coursePoints variable from the method below and display it.
coursePoints = coursePoints(grade,credits); //the method return a double value, assign it to the proper variable.

Your code works great, you just forgot this assignment. Perhaps you should not use the exact same name for variables and methods, it might be confusing.

I can't believe I've overlooked that. Thank you! Yeah this is my first program created using methods, I thought it would be simpler to use the same names but i've since learned otherwise!

This question has already been answered. Start a new discussion instead.