unexpected results - can please some one point the mistake - java

after spending number of hours and trying different things, i can't figure out what is wrong with my code, it's a simple program : `
public class AssignGrades {
private int ntotal=0;
private int []y;
//constructor to initialize class instances
AssignGrades(int t)
{
ntotal = t;
//y = num1;
}
AssignGrades( int []num1)
{
y=num1;
for (int i=0;i<y.length;i++)
y[i] = num1[i];
}
//method to sort grades int []num1
void setGrades()
{
int [] y = new int[ntotal];
for (int i=0;i<y.length;i++)
{
//assign grades
if
(y[i]<80){
System.out.println("grade is A" +y[i]);}
else if (y[i]<70)
System.out.println("grade is B" +y[i]);
else if (y[i]<60)
System.out.println("grade is c" +y[i]);
else
System.out.println("FAIL" +y[i]);
}
}
//show student grades - to print array[] values
void showGrades()
{
for (int u: y)
System.out.println(u);
}
}`
my client program
`import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int t=0;
System.out.println("enter no of students" );
Scanner input = new Scanner(System.in);
{
t=input.nextInt();
// input.close();
}
int [] num1 = new int[t];
System.out.println("enter grades");
Scanner input1 = new Scanner(System.in);
for (int i=0;i<num1.length;i++)
{
num1[i]=input1.nextInt();
}
input1.close();
AssignGrades ag = new AssignGrades(t);
AssignGrades ag1 = new AssignGrades( num1);
ag.setGrades();
ag1.showGrades();
}
}
output is:
enter no of students
2
enter grades
78
98
grade is A0
grade is A0
78
98
Question: now in the output 'A' and '0' -> where the problem is, it looks like array is not initialized, all the values appear to be zero: whereas when I print them separately, they are initialized.?!
Please let me know if more clarification is required. thanks

You have a local variable called y and a class variable with the same name y. That seems to be the problem. You are using the local y but you meant to use the class y, I think.
OK, your code had lots of problems. Here is the fixed version.
public class AssignGrades {
private int[] y;
public AssignGrades(int[] num1) {
y = num1;
}
// method to set grades
void setGrades() {
for (int i = 0; i < y.length; i++)
{
// assign grades
if (y[i] < 50)
System.out.println("FAIL" + y[i]);
else if (y[i] < 60)
System.out.println("grade is C" + y[i]);
else if (y[i] < 70)
System.out.println("grade is B" + y[i]);
else if (y[i] < 80) {
System.out.println("grade is A" + y[i]);
}
}
}
// method to show student grades
void showGrades() {
for (int u : y){
System.out.println(u);
}
}
}
import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
int t = 0;
System.out.println("enter no of students");
Scanner input = new Scanner(System.in);
t = input.nextInt();
int[] num1 = new int[t];
System.out.println("enter grades");
for (int i = 0; i < num1.length; i++) {
num1[i] = input.nextInt();
}
input.close();
AssignGrades ag = new AssignGrades(num1);
ag.setGrades();
ag.showGrades();
}
}

Related

How to connect two class modules together in Java?

I have a program that contains five .txt files. These files are read in and put into different arrays. One is an array of names. The other four are arrays with test scores.
Currently, the program does create the arrays correctly. Next the program is to calculate and display the average for each test (this works fine). Then the program prompts the user for a name. If a name is found a new menu will prompt the user to select which test they want the data on. (This works fine).
The problem: I have the main program class and another GradeBook class (does calculations) on another page. How do I connect the two pages together?
For example: If the studentName is 'Andrew' and it is found in studentNameArray, and I select 1 for which test score I want to see (scoreOneArray), say the number 88. My program finds 'Andrew' and '88'. What it does not do is send 'Andrew' and '88' to GradeBook to have the data compute test percentage (88/100) and find the corresponding letter grade (in this case 'B'). Lastly, then print students name, test score (88%), and the letter grade.
Program (main):
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
double test1Calculation;
double test2Calculation;
double test3Calculation;
double test4Calculation;
int i, j, k, l;
int testOneSum = 0;
int testTwoSum = 0;
int testThreeSum = 0;
int testFourSum = 0;
int checker = 0;
int index=0;
String choice;
Scanner students = new Scanner(new File("names.txt"));
Scanner TestOne = new Scanner(new File("testOne.txt"));
Scanner TestTwo = new Scanner(new File("testTwo.txt"));
Scanner TestThree = new Scanner(new File("testThree.txt"));
Scanner TestFour = new Scanner(new File("testFour.txt"));
String token1 = "";
List<String> studentName = new ArrayList<>();
while (students.hasNext()) {
// find next line
token1 = students.next();
studentName.add(token1);
}
String[] studentNameArray = studentName.toArray(new String[0]);
List<Integer> scoreOne = new ArrayList<>();
// while loop
while (TestOne.hasNext()) {
// find next line
Integer token2 = TestOne.nextInt();
scoreOne.add(token2);
}
Integer[] scoreOneArray = scoreOne.toArray(new Integer[0]);
List<Integer> scoreTwo = new ArrayList<>();
// while loop
while (TestTwo.hasNext()) {
// find next line
Integer token3 = TestTwo.nextInt();
scoreTwo.add(token3);
}
Integer[] scoreTwoArray = scoreTwo.toArray(new Integer[0]);
List<Integer> scoreThree = new ArrayList<>();
// while loop
while (TestThree.hasNext()) {
// find next line
Integer token4 = TestThree.nextInt();
scoreThree.add(token4);
}
Integer[] scoreThreeArray = scoreThree.toArray(new Integer[0]);
List<Integer> scoreFour = new ArrayList<>();
// while loop
while (TestFour.hasNext()) {
// find next line
Integer token5 = TestFour.nextInt();
scoreFour.add(token5);
}
Integer[] scoreFourArray = scoreFour.toArray(new Integer[0]);
for (i = 0; i < scoreOneArray.length; i++)
testOneSum += scoreOneArray[i];
test1Calculation = (double) testOneSum / 5;
for (j = 0; j < scoreTwoArray.length; j++)
testTwoSum += scoreTwoArray[j];
test2Calculation = (double) testTwoSum / 5;
for (k = 0; k < scoreThreeArray.length; k++)
testThreeSum += scoreThreeArray[k];
test3Calculation = (double) testThreeSum / 5;
for (l = 0; l < scoreFourArray.length; l++)
testFourSum += scoreFourArray[l];
test4Calculation = (double) testFourSum / 5;
System.out.println("The average for test one is: " + test1Calculation);
System.out.println("The average for test two is: " + test2Calculation);
System.out.println("The average for test three is: " + test3Calculation);
System.out.println("The average for test four is: " + test4Calculation);
Scanner studentSearch = new Scanner(System.in);
System.out.println("Enter student name : ");
String foundStudent = studentSearch.nextLine();
boolean found = Arrays.stream(studentNameArray).anyMatch(t -> t.equals(foundStudent));
if (found) {
index++;
System.out.println(foundStudent + " is found.");
//menu loop
do {
//displayed user options
System.out.println("1. To find score for first test");
System.out.println("2. To find score for second test");
System.out.println("3. To find score for third test");
System.out.println("4. To find score for fourth test");
//menu choices
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter your choice: ");
choice = keyboard.next();
if (choice.equals("1")) {
int score= scoreOneArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("2")) {
int score= scoreTwoArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("3")) {
int score= scoreThreeArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("4")) {
int score= scoreFourArray[index];
System.out.println(score);
checker = -1;
} else {
//Error message
System.out.println("invalid choice");
}
}
while (checker != -1);
} // End of Menu Method
else {
System.out.println(foundStudent + " is not found.");}
students.close();
TestOne.close();
TestTwo.close();
TestThree.close();
TestFour.close();
}
}
Calculations(GradeBook):
import java.util.ArrayList;
public class GradeBook {
private char[] letterGrade = {'A', 'B', 'C', 'D', 'F'};
private ArrayList<String> names = new ArrayList<>();
private double [][] scores = new double[5][4];
public GradeBook(ArrayList<String> studentNames, double[][] studentScores){
this.names = studentNames;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 4; j++){
scores [i][j] = studentScores[i][j];
}
}
}
public String getName(int studentIndex){
return names.get(studentIndex);
}
public double getAverage(int studentIndex){
double total = 0;
for (int i = 0; i < 4; i++){
total += scores[studentIndex][i];
}
return (total / 4);
}
public char getLetterGrade(double avgScore){
if (avgScore >= 90 && avgScore <= 100){
return letterGrade[0];
}
else if (avgScore >= 80 && avgScore <= 89){
return letterGrade[1];
}
else if (avgScore >= 70 && avgScore <= 79){
return letterGrade[2];
}
else if (avgScore >= 60 && avgScore <= 69){
return letterGrade[3];
}
else if (avgScore >= 0 && avgScore <= 59){
return letterGrade[4];
}
return ' ';
}
public void getStudent(){
for (int i = 0; i < names.size(); i++){
System.out.println("\nStudent #" + (i+1)
+"\n\t\tName: " + names.get(i)
+"\n\t\tAverage: " + getAverage(i) + "%"
+"\n\t\tLetter Grade: " + getLetterGrade(getAverage(i))
+"\n\n");
}
}
}
I don't understand how much of what's going on in GradeBook relates to what you're doing in your main function. I see how in your main you're coming up with a single score based on the user's selection of a student and a test number. But once you have this user and score, I don't see how that matches up with the data in the double[][] studentScores table contained in GradeBook. What is that data? Where does it come from?
Your code in main seems to have a significant problem. index will always be 1 by the time it's used. Its value is not affected by what is entered as a student name. I think you mean for it to be. Also, I don't understand how the single integer score you come up with in main matches up with the avgScore accepted by the GradeBook. But ignoring all of that...
It seems like you'd have just a single GradeBook, right? So I think you'd instantiate just a single instance of it, and then you could use it to look up the student's name and to calculate the grade based on the student's score. Assuming that index matched up with the names list in GradeBook, and you somehow computed an averageScore, that would look something like this...
public class Main {
public static void main(String[] args) throws IOException {
...
GradeBook gradeBook = new GradeBook(...);
...
while (...) {
index = ...
...
averageScore = ...
...
studentName = gradeBook.getName(index);
grade = gradeBook. getLetterGrade(averageScore);
System.out.println(String.format("Student: %s. Grade: %s", studentName, grade));
}
The other use case I can see is that you'd calculate somehow calculate the studentScores table from the data you read in main, and then you could create a GradeBook with that to have it display all of that information. That would look like this...
studentScores = ...
...
GradeBook gradeBook = new GradeBook(studentScores);
gradeBook.getStudent()

How to insert a value in 2D array in java

How can I fill a 3x3 matrix using a 2D array such that the user picks what
position of the array they want to input their String value?
The position format is: (Row Number, Column Number)
For example:
Person 1, please pick where to place an X: (0,1)
Person 2, please pick where to place an O: (0,2)
This is what I have:
import java.util.Scanner;
public class idk {
public static void main(String[] args)
{
int i;
int j;
int arr[][] = new int[3][3];
// Getting user input
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = input.nextInt();
}
}
// Outputting the user input
System.out.println("The output is: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.printf("%d ", arr[i][j]);
}
}
}
}
Something like the following has most of the parts you would want, except for error handling. Input is number, space (or any whitespace), finally followed by another number. Input numbers are 1 to 3 inclusive, which is what a normal person would expect.
import java.util.Scanner;
public class TicTacToe {
char board[][] = new char[][]{{'-','-','-'},{'-','-','-'},{'-','-','-'}};
public static void main(String[] args) {
TicTacToe ttt = new TicTacToe();
ttt.run();
}
public void run() {
Scanner input = new Scanner(System.in);
int row = -1, col = -1;//just to initialize
char symbol = 'o';
while (true) {
symbol = (symbol == 'x')?'o':'x';
boolean error = false;
System.out.println("Enter a number: ");
if (input.hasNext()) {
row = input.nextInt();
System.out.println("row: " + row);
} else {
error = true;
}
if (input.hasNext()) {
col = input.nextInt();
System.out.println("col: " + col);
} else {
error = true;
}
if (!error) {
board[row - 1][col - 1] = symbol;
}else{
System.out.println("an error has occurred");
}
input.reset();
this.drawBoard();
}
}
public void drawBoard() {
System.out.println("The output is: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%c ", board[i][j]);
}
System.out.println();
}
System.out.println();
}
}
If you look up Scanner you will see an example to parse using a regex, I like that method better since with a regex you can validate the whole string at once but since that was not in the questions code I didn't use that method.
Simply
arr[Row Number][Column Number]=X;
eg
arr[0][1]=X;
or
arr[1][0]=O;
but because it is an int array you cannot place String i.e "O" and "X" in it.
Try making it an String array

Calling void methods from main method, cannot pass arguments within void methods

my teacher asked us to create an additive prime program for my computer science class. I have created all my void methods, and believe to have all the math logic figured out. However, when I try to pass arguments into the instances of my methods within my main method, It gives me an error saying:
it can not find the variable in this case variable 'x'
package additiveprimes;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author talarik048
*/
public class AdditivePrimes {
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public void userInput(String x){
Scanner sc = new Scanner(System.in);
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
}
public void isPrime(String x){
this.userInput(x);
boolean prime = true;
int y = Integer.parseInt(x);
for(int i = 0; i < y; i++){
if(y % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is prime...");
} else {
System.out.println("Your number is not prime...");
}
}
}
public void numArray(String x){
this.userInput(x);
String[] strArray = x.split("\\s+");
boolean prime = true;
int[] numbArray = new int[strArray.length];
for(int j = 0; j < strArray.length; j++){
try{
numbArray[j] = Integer.parseInt(strArray[j]);
} catch(NumberFormatException e){
System.out.println("ERROR");
}
for(int i = 0; i < numbArray.length; i++){
int sum = (Arrays.stream(numbArray).sum());
if(sum % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is an additive prime...");
} else {
System.out.println("Your number is not an additive prime...");
}
}
}
}
}
I think you wanted to RETURN a value from userInput:
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(Exception e){// see OH GOD SPIDERS comment
System.out.println("Error, try again: ");
x = sc.nextLine();//this is not a good way for a retry
}
return x;
}
Alternatively you could make x a field.
Your methods accept a string as an argument, but you have not passed any. You need to initialize x in main.
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x= "55";
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
Note
Although the above code fixes your current issue. It doesn't seem to be the correct way to use this class. You should probably be calling .userInput() method and getting the userInput then passing it to your other methods.
You could probably change your overall class to
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
return x;
}
You have not defined x as anything before using it. Try defining x. In this case since your arguments are strings, I recommend...
String x = new String();

Changing input variables in a java loop

I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}

how to transverse arraylist

I need to know how to transverse my average function into this result function if u are getting ?
This is the main class:
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList < Calculations > students = new ArrayList < Calculations > ();
for (int i = 0; i < 5; ++i) {
Calculations s = new Calculations();
System.out.print("Enter name : ");
s.name = scan.next();
System.out.print("Eter percentage : ");
s.percetage = scan.nextDouble();
students.add(s);
System.out.println("Enter Mrks Obtained");
}
for (Calculations s: students) {
s.result();
for (Calculations i: students) {
s.Average();
}
}
}
}
This is result class:
import java.util.Scanner;
public class Calculations {
public String name;
public double percetage;
public int integer;
public void result() {
System.out.println((percetage >= 35.0 f ? (name + " Pass") : (name + " Fail")));
}
public void Average() {
// TODO Auto-generated method stub
int mark[] = new int[5];
int i;
float sum = 0;
float avg, perc;
Scanner scan = new Scanner(System.in);
System.out.print("Enter marks Obtained in 5 Subjects : ");
for (i = 0; i < 5; i++) {
mark[i] = scan.nextInt();
sum = sum + mark[i];
}
avg = sum / 5;
perc = (sum / 500) * 100;
System.out.print("Average Marks = " + avg);
System.out.print("\nPercentage = " + perc + "%");
}
}
for(Calculations s : students){
s.result();
//for(Calculations i : students){s.Average(); }
s.Average();
}
you dont have to loop your arraylist twice. try changing your code.
It was so hard to follow through your incomplete question, which is not specific either. Your program works fine in my eclipse. I would suggest following:
1) Check the name of the fields/ spelling in you Calculations class to match exactly as it's been used in the main class.
2) Since you're inputting String Scanner, try to read lines as follows:
s.name = scan.nextLine();
I hope it helped.

Categories