BegCoder BegCoder - 7 months ago 6
Java Question

How to add two numbers accepted in String form in Java?

So I am trying to create a program which calculates the grades of a student with a specified formula that multiplies the grade of the test with 0.5 and the oral grade with 0.4.

import java.util.Scanner;

class name {
public static void main (String[] args){
Scanner input= new Scanner(System.in);
name nameObject = new name();
System.out.println("Enter your calculated math test grade here: ");
String grade= input.nextLine();
System.out.println("Enter your calculated math oral grade here: ");
String oral= input.nextLine();
System.out.println("Your final grade is " oral + grade);
}
}


The problem is that when I run it it doesn't add the two strings normally. For example if the oral grade is 6 and the test grade is 1 doesn't print out 7 but 61

Answer

What you want to do can be done like this:

Scanner input= new Scanner(System.in);
System.out.println("Enter your calculated math test grade here: ");
// Convert the test grade into an Integer
int grade= Integer.parseInt(input.nextLine());
System.out.println("Enter your calculated math oral grade here: ");
// Convert the oral grade into an Integer
int oral= Integer.parseInt(input.nextLine());
// Add the two Intergers by doing the addition inside parenthesis
// otherwise it still does string concatenation like before 
System.out.println("Your final grade is "+  (oral + grade));

Output:

7