I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The method getSum(int[]) is undefined for the type
UserInteraction The method getAverage(int[]) is undefined for the type
UserInteraction at UserInteraction.main(UserInteraction.java:66)
Here's the code of the first class:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
Grades method = new Grades();
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
}
And the second class is:
public class Grades {
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ( ( double ) sum )/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line
To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));
Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.
You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.
Related
I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
The Code below I tried got to work correctly. When I go to "Run As" in Eclipse, the Console shows nothing and the output is blank. Please help. NOTE I took out the public class & import java because the post wasn't loading the code correctly.
public static void main(String[] args ) {
// Create new Scanner
Scanner input = new Scanner(System.in);
// Set number of students to 10
int numStudents = 10;
// Note
int [][] studentData = new int[numStudents][1];
// loop
for (int i = 0; i > numStudents; i++) {
// Note
boolean classesValidity = true ;
while (classesValidity == false) {
System.out.print("Enter classes and graduation year for student’" +
(i + 1) + " : " );
int numClasses = input.nextInt();
studentData [i][0] = numClasses;
int gradYear = input.nextInt();
studentData [i][1] = gradYear; }
for (int i1 = 0; i > numStudents; i ++) { System.out.println("\n Student " + ( i ) + " needs " +
studentData [i][0]*3 + " credits to graduate in " + studentData [i][1]); }}}}
classesValidity is initialized with true and remains unchanged. In turn the while loop is never executed and the program only iterates through studentData without operating on it.
Idea:
User inputs their bets by typing either 'W','L' or 'T' (wins, losses or tie). Program generates random results within these parameters. User input and result gets printed, and a score is presented based on correct bets, which is supplied by the program.
Im having issues on how to proceed with comparing user generated input from scanner to an arraylist that produces a random result.
If it were not for the multiple "questions" and "answers" I could use a (val.equals(input)) of sort. However, each individual bet is random and must be matched against the users bets to sum up the users score, that complicates it.
Any help appreciated.
public class test3 {
public static void main(String[] args) {
int score = 0;
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
test3 obj = new test3();
for(int i = 0; i < 5; i++){
System.out.print(obj.getRandomList(list) + " ");
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private Random random = new Random();
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
One way to do this is in the code below.
You basically need to compare each element of your input with each element of the random list so run loop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Test {
private Random random = new Random();
public static void main(String[] args) {
int score = 0;
System.out
.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your bet:");
array[i] = input.nextLine();
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++) {
System.out.print(array[i] + " ");
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
Test obj = new Test();
List<String> randList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
randList.add(obj.getRandomList(list));
}
for(String randBet : randList){
System.out.print( randBet + " ");
}
System.out.println("");
int counter = 0;
for (String yourbet: Arrays.asList(array)){
if(randList.get(counter).equals(yourbet)){
score++;
}
counter++;
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
I removed test3 for simplicity, but basically you need save results on array and generate random results and saving them (i.e a list). Then you have to iterate through and compare each game result, and if your bet is correct, just add one to score. Check the code below:
Main:
public static void main(String[] args) {
int score = 0;
String array[] = new String[5];
List < String > randomResultList = new ArrayList<String> ( );
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
for(int i = 0; i < 5; i++){
String randomResult = getRandomList();
System.out.print( randomResult + " ");
randomResultList.add ( randomResult );
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
//here is where you compare each result
for(int i = 0; i < 5; i++)
{
if( array[i].equals ( randomResultList.get ( i ) ))
{
score++;
}
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private static Random random = new Random();
public static String getRandomList() {
List<String> list = Arrays.asList("w", "l", "t");
int index = random.nextInt(list.size());
return list.get(index);
}
I/O Example:
Betting game initiating...
Type 'W' for win, 'L' for loss and 'T' for tie.
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
This week wins, losses and ties loading...
Result:
l l l t w
Your bets were:
w w w w w
You were correct on: 1 bettings
Extra:
You could do all on the same iteration! check this out.
public static void main(String[] args) {
int score = 0;
// Win Loose or Tie
List<String> list = Arrays.asList("w", "l", "t");
Random rand = new Random ( );
//String with result and bets i.e (wwwww) and (wlltw). This avoid another iteration.
String result="";
String bets = "";
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
String bet =input.nextLine();
String randomResult = ( list.get ( rand.nextInt ( list.size ( ) ) ));
//concatenate String with results and bets with +=
result += randomResult;
bets += bet;
//check if u won
if( bet.equals ( randomResult ))
{
score++;
}
}
//This are just the results! no more iterations.
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:" + result);
System.out.println("\n\nYour bets were:" + bets );
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)
I cant figure out how to add the values after it spits out the numbers.
it says:
Number: 5 // I typed 5
1 2 3 4 5
The sum is.
So i need to add those number 1 2 3 4 5 but cant figure out how.
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + 1 ;
}
System.out.println( "The sum is . " );
}
}
You need to add run to sum and then print it out, like this:
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + run;
}
System.out.println( "The sum is " + sum );
}
}
System.out.println( "The sum is: " + sum );
the + sum seems weird but you can use it the and a number value to a string
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
I believe you want sum = sum + run;
if you are wanting to sum (1, 2, 3, 4, 5) = 15.
Fahd's answer is pretty much what you're looking for (he posted while I was typing mine). My answer just has a little bit different syntax to perform the loop and sum.
import java.util.Scanner
public class AddingValuesWithAForLoop { public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run++)
{
System.out.print( run + " " );
sum += run;
}
System.out.println( "The sum is " + sum + "." );
}
}
well the way your doing it you will need to do keyboard.nextLine(); that will set all of your numbers to a string. Once you have all of your numbers in string you can parse through the string and set that as the scanner then do nextInt()
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Number: ");
string numbers = keyboard.nextLine(); // 5 1 2 3 5
Scanner theNumber = new Scanner(numbers);
int sum = 0;
for (int run = theNumber.nextInt(); run > 0; run--)
{
System.out.print(run + " ");
sum += theNumber.nextInt();
}
System.out.println("The sum is: " + sum);
}
}
Here is the code that might be helpful:
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
Hope this answer help you.
Assume that input value is 6, So internally add all the consecutive numbers until 6. I.e Since the input value is 6, output should be like this
0+1+2+3+4+5=15
Refer to the below snippet
public void testAdding() {
int inputVal = 6;
String input = "";
int adder = 0;
for(int i=0; i < inputVal; i++) {
input = String.valueOf(i);
if(inputVal == (i+1)) {
System.out.print(input);
} else {
System.out.print(input+"+");
}
adder =+ i + adder;
}
System.out.print("="+adder);
}