I am a beginner in Java programming and I want to know : What does it mean by or it's function:
obtainedMarks = se.nextInt();
in this code :
package ifstatment;
import java.util.Scanner;
public class Ifstatment {
public static void main(String[] args) {
int obtainedMarks ;
int passingMarks;
String grade;
Scanner se = new Scanner(System.in);
System.out.println("Enter your scoor");
passingMarks = 40 ;
obtainedMarks = se.nextInt();
if (obtainedMarks >= passingMarks ){
if (obtainedMarks > 90)
grade = "A";
else if (obtainedMarks > 75)
grade = "B";
else if (obtainedMarks > 65)
grade = "C";
else
grade ="D";
System.out.println("You passed the exam and your grade is"+ grade);
} else {
grade = "F";
System.out.println("You failed in thee exam and your grade is " + grade);
}
}
}
You are reading an int from the console and saves it to the obtainedMarks variable.
You can read more about Scanner here
se.nextInt()
reads the next int value from the input stream (System.in in your case) and returns that value.
obtainedMarks = se.nextInt()
"takes" that value and assigns it to the variable obtainedMarks.
se.nextInt()
This mean that you will input an integer from console and assign it to var obtainedMarks
Please access this link for more information.
Related
I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}
Hi I am fairly new to java and trying to familiarize myself to it by doing some exercises online.
How do i properly code the while loop so that everytime the user input is wrong it asks the same question again and does not proceed to the next line of code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
boolean checker = true;
while (checker){
for (int i = 0; i < entries; i++){
int input;
int addToList;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
grade.add(input);
if (input >= 0 && input<= 100) {
}else {
System.out.println("invalid input try again..");
checker = false;
}
}
}
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade){
sum+= grades;
}
mean =(double)sum/count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
Your logic is backwards. You want the loop to continue if the input is incorrect. There are two ways to fix this:
Change while(checker) to while(!checker)
Change checker=false to checker=true after printing the error message. And set checker=false in the if branch.
It might help if you change the name of your checker variable to something that reads more directly. For example isInputCorrect reads very nicely when you write while(!isInputCorrect) and it also makes it more clear what the values of true and false represent.
try this :
boolean checker = true
for(int i=0;i< entries;i++){
int input;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
while(checker){
if(input >= 0 && input<= 100){
grade.add(input);
checker = false;
}else{
System.out.println("invalid input try again..");
}
}
checker = true;
}
You could try this
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
for (int i = 0; i < entries; i++) {
int input;
do{
input = dataIn.nextInt();
if (input >= 0 && input <= 100) {
grade.add(input);
}else{
System.out.println("invalid input try again..");
}
}while(!(input >= 0 && input <=100));
}
dataIn.close();
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade) {
sum += grades;
}
mean = (double) sum / count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
instead of doing while(checker)
make a loop for while(running)
then send it to the keyboard.nextInt()
if its the wrongAnswer than it will loop, if its correct than set running to false
and have code that follows the while loop
I need help making a program that will take the int input of the user as the number of students. At the moment I have to manually add the students in the code if I want more student. ive added my other class aswell. please help if possible.
import java.util.Scanner;
// the name of our class its public
public class ClassArray {
//void main
public static void main (String[] args){
//declare class
Student[] s = new Student[2];
s[0] = new Student();
s[1] = new Student();
//call functions
s[0].getdata();
s[1].getdata();
s[0].finalmark();
s[1].finalmark();
s[0].finalgrade();
s[1].finalgrade();
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
s[0].print();
s[1].print();
}
}
}
//declare class
public static class Student {
//declare variables.
private Double finalmark;
private int test1,test2,assignments1,finalexam;
private String studentname,finalgrade;
//functions should be public if needed to access from other class
public void getdata()
{
//print message to enter numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter name of student:");
studentname = input.next();
while (!studentname.matches("[a-zA-Z]+")) { // Checks to see if only letters are used in the name
System.out.println("Please re-enter your name, use alphabets only");
studentname = input.nextLine(); // if anything other than letters are used, the user must re-enter his/her name using letters
}
System.out.println("Enter mark test 1 for student:");
test1 = input.nextInt();
while (test1 > 100 || test1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next();
}
test1 = input.nextInt();
}
System.out.println("Enter mark test 2 for student:");
test2 = input.nextInt();
while (test2 > 100 || test2 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
test2 = input.nextInt();
}
System.out.println("Enter mark assignments for student:");
assignments1 = input.nextInt();
while (assignments1 > 100 || assignments1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
assignments1 = input.nextInt();
}
System.out.println("Enter mark final exam for student:");
finalexam = input.nextInt();
while ( finalexam > 100 || finalexam < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
finalexam = input.nextInt();
}
}
public void finalmark(){
finalmark = (test1 * 0.15) + (test2 * 0.25) + (assignments1 * 0.25) + (finalexam *
0.35);
}
public void finalgrade()
{
if(finalmark >= 100)
finalgrade="A+";
else if(finalmark >= 90)
finalgrade="A+";
else if(finalmark >= 80)
finalgrade="A";
else if(finalmark >= 75)
finalgrade="B+";
else if(finalmark >= 70)
finalgrade="B";
else if(finalmark >= 65)
finalgrade="C+";
else if(finalmark >= 60)
finalgrade="C";
else if(finalmark >= 50)
finalgrade="D";
else
finalgrade="F";
}
public void print(){
System.out.printf("%s\t%.2f\t%s\t%d\t%d\t%d\t\t%d\n", studentname, finalmark,
finalgrade, test1, test2, assignments1, finalexam);
}
}
Something like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Your complete code would be:
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Student[] s = new Student[numStudents];
for(int i = 0; i < numStudents; i++ ){
s[i] = new Student();
s[i].getdata();
s[i].finalmark();
s[i].finalgrade();
}
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
//Here it will iterate and print out the stored data as soon as the user has finished adding it.
for(int j = 0; j < numStudents; j++ ){
s[j].print();
}
}
Simply,
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args) {
Scanner input= new Scanner(System.in); // create Scanner object
System.out.print("Enter The Number of Students: ");
int numOfStudents = input.nextInt(); // input an integer value
// do whatever you like
}// Ends main
}
Here I created an object of class Scanner as input and I've called the method nextInt() by the object of class Scanner (input).
See this post for user input: How can I get the user input in Java?
You also should not use an array which you have defined as having a set number of elements, in your example 2. Instead, consider an ArrayList of objects type Student which for your purposes can accept any number of Students.
ArrayList<Student> s = new ArrayList<Student>();
//Example add student
Student student1 = new Student();
s.add(student1);
See this post for ArrayList: Java: ArrayList of String Arrays
java methods statithing but I can't seem to get my while statement on line 56 to call my methods properly. Is there something that I'm doing wrong? I am very new to Java so any sort of help would be appreciated! Thanks in advance!
Here is my code:
import java.util.*;
import javax.swing.*;
import java.io.*;
public class GradeCalculator {
static String fileInput;
static double totalGrade;
static int scoreCount= 0;
static double classAverage;
static double score;
static double testScore;
static double averageScore;
static int numberOfStudents = 0;
static char letterGrade;
static String fileOutput;
static String nameOfStudent;
static int numberCount;
static int numberCalculatedStudents;
static double average = 0;
public static void main (String[] args) throws FileNotFoundException {
//Welcome
JOptionPane.showMessageDialog(null,"Welcome to the Grade Calculator! This program will\n" +
" calculate the average percentage of 5 test scores that\n"+
" are given in a given file once these scores are\n"+
" averaged it will give the student a letter grade.","Welcome!",JOptionPane.PLAIN_MESSAGE);
fileInput = JOptionPane.showInputDialog(null, "Please enter the name of the input file you wish to use for this program."
,"Input File",JOptionPane.PLAIN_MESSAGE);
fileOutput = JOptionPane.showInputDialog(null, "Please enter the name of the output file you wish to use for this program."
,"Output File",JOptionPane.PLAIN_MESSAGE);
//preparing text files
PrintWriter outFile = new PrintWriter (fileOutput);
File inFile = new File (fileInput);
Scanner reader = new Scanner(new FileReader(fileInput));
outFile.println("Student Name Test1 Test2 Test3 Test4 Test5 Average Grade");
while(reader.hasNextLine()) {
nameOfStudent = reader.next();
outFile.printf("%n%n%s",nameOfStudent);
numberOfStudents++;
score = reader.nextDouble();
calculateAverage(score);
calculateGrade(averageScore);
outFile.printf(" %.2f ", averageScore);
outFile.println(" "+letterGrade);
}
classAverage = classAverage/numberCalculatedStudents;
outFile.print("\n\n\n\n\n\n\n\n\n\n\n\nClass average for "+ numberCalculatedStudents + "of" + numberOfStudents + "is" + classAverage);
JOptionPane.showMessageDialog(null,"The report has successfully been completed and written into the file of " + fileOutput +"."
+" The class average is " + classAverage + ". Please go to the output file for the complete report.");
outFile.close();
}
public static void calculateAverage(double score) throws FileNotFoundException {
Scanner reader = new Scanner(new FileReader(fileInput));
PrintWriter outFile = new PrintWriter (fileOutput);
while (reader.hasNextDouble() && numberCount <= 5 ) {
score = reader.nextDouble();
numberCount++;
if (score >= 0 & score <= 100) {
outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);
}
if (average!=0){
numberCalculatedStudents++;
average = average/scoreCount;
averageScore = average;
classAverage = average + classAverage;
}
average = 0;
}
public static char calculateGrade (double averageScore) {
if (averageScore >= 90 && averageScore <= 100)
letterGrade = 'A';
else if (averageScore < 90 && averageScore >= 80)
letterGrade = 'B';
else if (averageScore < 80 && averageScore >= 70)
letterGrade = 'C';
else if (averageScore < 70 && averageScore >= 60)
letterGrade = 'D';
else if (averageScore < 60 && averageScore >= 0)
letterGrade = 'F';
else
letterGrade =' ';
return letterGrade;
}
}
Without knowing what line the problem is arising on, two issues jump out at me:
At the top of the while loop:
if (score >= 0 & score <= 100)
{ outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);}
You have a close bracket (}) after the else statement, but no open bracket. So that close bracket looks like its exiting the while loop before you want it to.
Second, it looks like you're trying to return something (namely a char) in your CalculateGrade method, but you have specified a return type of void on it, which means that even though you have a return statement, nothing gets returned when you call it. You don't show where you're calling that method, so I can't be sure this is causing a problem, but its certainly suspect. It seems like you want to use:
public static char calculateAverage(double score) throws FileNotFoundException{
instead of public static void calculateAverage(double score)...
Also, is there a reason why all of these methods are static? Do you know what making something static means?
EDIT (based on your comment):
No. making a variable static makes it a "class variable", which means that only one of them exists for all objects of that class. To illustrate:
If you have a class like this:
class test {
static int id;
}
And you run the following code:
test t1 = new test();
test t2 = new test();
t1.id = 4;
t2.id = 8;
System.out.println(t1.id);
it will print 8. This is because, since id is a static variable changing it on any object of the class will cause it to change for every other object of the class.
This is as opposed to an "instance variable" one of which exists for every object of the class. To make id an instance variable, simply remove the static keyword. If you do so and run the same code, it will print 4, because changing an instance variable of t2 has no effect on t1.
Make sense?
import java.util.Scanner;
public class EP55Out
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
// getNumericGrade(grade);
}
public static void getNumericGrade(double grade)
{
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}
I don't know if you guys understand what I mean, but I keep getting the error that "grade" does not exist even though it is defined in the main. I know it has something to do with "void" but I have no clue what. Can anybody help?
So you are learning Java don't you?
I'll try to explain what you are doing wrong.
import java.util.Scanner;
public class EP55Out {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
//You need to give letter to the method
getNumericGrade(letter);
}
//AND the method should need String and not double
public static void getNumericGrade(String letter){
//After this you need a real double value - lets call is grade;
double grade = 0;
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
//You cant to numeric stuff with a String- thats why we use our double here
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade+"");
}
}
You missed an important point with variables...
If you define a variable in a method - it is only visible in THE DEFINING METHOD!
So
public static void getNumericGrade(String letter)
cannot know that there is a letter variable in
public static void main(String[] args)
Hope I could help you ;)
If I understood correctly, and If u r getting error on the line that u have commented...
then "grade" really does not exist, The name of variable is "letter"
can u plz try running this code and see if it works.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
getNumericGrade(letter);
}
public static void getNumericGrade(String letter)
{
int spacer = 0;
double grade;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}
grade is not defined in main. What you are looking for is letter,
String letter = in.next();
getNumericGrade(letter);
However, this will not solve your problem, as the getNumericGrade method requires you to pass it a double. I think (based on the method name), that you really want getNumericGrade to accept a String, and return a double. I would try referring to your textbook or tutorial some more, as you haven't grasped methods quite yet I don't think.
In particular, the void means that a method doesn't return a value. void can be replaced with any type, like int or String or even SomeClass. On the same line, inside the parentheses is where you specify what arguments your method will accept. These can be of any type, and you can name them anything you want, they don't have to correspond to the names of the variables you pass to a method call. So, if I had a method getAverageGrade which accepted a String argument (say the name of a student) and returned a double which is the current average grade for that student, the method signature, or definition would look something like this
public double getAverageGrade(String studentName)
Hopefully that should get you started down the right path.
i think you should do like this way
import java.util.Scanner;
public class EP55Out
{
String letter = "";
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
letter = in.next();
getNumericGrade();
}
public static void getNumericGrade()
{
if(letter.length()<=0)
return;
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}