How to show the contents of an array correctly - java

I'm trying to make a test correction simulator, that the user enters the test feedback at first an then the numbers of students in the class, the name and finally the answers.But the problem is: when I try to show the student names and the answer...they are below the other.So how I can fix this?
This problem is because i'm making two for's instead of one?So i can't display the student names and the answer correctly?
And my other problem is the score of the students.How I make it for each student and show it on the side.
Check my Stack trace below for a better understanding:
import java.util.Scanner;
public class testArray {
public static void main(String[] args) {
int score = 0, n, i, j = 0;
Scanner sc = new Scanner(System.in).useDelimiter("\r\n");
System.out.print("How many students in the class?: ");
n = sc.nextInt();
String name[] = new String[n];
char answer[][] = new char[n][5];
float media[] = new float[n];
char testFeedback[] = new char[5];
int socreArray[] = new int[n];
System.out.println("--Type (a,b,c,d or e)--");
for (int g = 0; g < testFeedback.length; g++) {
System.out.print("TestFeedback | question[" + g + "]: ");
testFeedback[g] = sc.next().charAt(0);
}
for (i = 0; i < n; i++) {
System.out.print("Student name: ");
name[i] = sc.next();
for (j = 0; j < 5; j++) {
System.out.println("answer nº" + (j + 1) + ": ");
answer[i][j] = sc.next().charAt(0);
if (answer[i][j] == testFeedback[j]) {
score++;
}
}
System.out.println("Score: " + score);
}
System.out.println("\nGeneral report: ");
System.out.println("Student - answer - score");
for (i = 0; i < n; i++) {
System.out.println(name[i]);
}
for (j = 0; j < n; j++) {
System.out.println(answer[j]);
}
if (score > 3) {
System.out.println("Congratulations, you went well!");
} else {
System.out.println("Too bad, you need to study more.");
}
}
}

If I understood your question correct, to show names and answer you could use 1 for:
for (i = 0; i < n; i++) {
System.out.print(name[i] + ": ");
for(int j = 0; j < answer[i].length; j++) {
System.out.print(answer[i][j] + " ");
}
System.out.println();
}
To show score, you have to store it somewhere, for example in anotherarray or list.

Yeah the problem is that you're outputting the students in a loop THEN you're outputting the answers in another loop. This should happen in the same loop so that you output a student and their answers in the same loop cycle.
Given that your student array and answer array are the same size (each student has a corresponding answer at the same index), you could do this:
for(int i = 0; i < n; i++) {
System.out.println(student[i]);
System.out.println(answer[i]);
}
Storing data in two parallel arrays is a bit awkward because you have to make sure that you update them together. This would be a good time to think about using some extra classes to represent the entities in your project and keep related things together.

You need a string builder in your for loop above the System.out.println( "General Report" );
You don't need the next two for loops. Move the
System.out.println( "General Report" );
System.out.println( "Student - answer - score " );
above this loop.
and move if ( score > 3) else inside your loop as in below code. You can delete everything after this loop.
System.out.println("\nGeneral report: ");
System.out.println("Student - answer - score");
for (i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
System.out.print("Student name: ");
name[i] = sc.next();
for (j = 0; j < 5; j++) {
System.out.println("answer nº" + (j + 1) + ": ");
answer[i][j] = sc.next().charAt(0);
sb.append( String.valueOf(answer[i][j]) );
if (answer[i][j] == testFeedback[j]) {
score++;
}
}
System.out.println( name[i] + " - " + sb.toString() + " - " + score );
if (score > 3) {
System.out.println("Congratulations, you went well!");
} else {
System.out.println("Too bad, you need to study more.");
}
}

Related

JOptionPane Looping

I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

looping through array - only first index printing

I want to loop through an array and print any values that are not null, here is the code I am trying to use:
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
}
}
Array:
static String[] studentNamesArray = new String[10];
The problem is that it is only printing out index[0]. How can I fix this?
EDIT:
Here is my full code:
static void deleteStudent() {
boolean studentFound = false;
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for (i = 0; i < 10; i++) {
for (i = studentChoice + 1; i < studentNamesArray.length; i++) {
studentNamesArray[i - 1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount - 1;
studentNamesArray[studentNamesArray.length - 1] = null;
for (i = studentChoice + 1; i < 9; i++) {
for (int y = 0; y < 3; y++) {
studentMarksArray[i - 1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for (int y = 0; y < 3; y++) {
studentMarksArray[9][y] = 0;
}
}
}
if (!studentFound) {
System.out.println("There are no students stored");
}
}
Use the for-loop only to print the students names. And read the studentChoice once after you printed all the students. Otherwise it waits for input after printing the studentNamesArray[0]
System.out.println("Which student would you like to delete?");
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println(i + ": " + studentNamesArray[i]);
}
}
int studentChoice = input.nextInt();
Make sure that the contents of the array are not null, or they wont print out
Only reason I can see here, other elements should be null. You can make sure it as follows
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();// you need to check this
}else{
System.out.println(i + ": " + studentNamesArray[i]);
}
}
But may be there is another reason. If input.nextInt() is take from Scanner, your program will wait there for a user input. Then you have to provide that input to continue. Make sure those things.

Java Grade Calculator program for class kepp geting the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException."

This is my first question I've posted. I've used this site to look at other questions to help with similar problems I've had. After some cursory looking I couldn't find quite the answer I was looking for so I decided to finally succumb and create an account.
I am fairly new to java, only a few weeks into my first class. Anyway, my project is to create a program which takes any amount of students and their grades, and then assign them a letter grade. The catch is, however, that it is on a sort of curve and the other grades' letter are dependent on the the highest. Anything equal to or 10 points below the best grade is an a, anything 11-20 points below is a b, and so on. I am to use an array, but I get this error when ran "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException."
I will go ahead and post my code down below. Thanks for any advice you may be able to give.
package grade.calculator;
import java.util.Scanner;
/**
*
* #author nichol57
*/
public class GradeCalculator {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of students");
int number = input.nextInt();
double[]grades = new double [number];
for (int J = number; J >=0; J--) {
System.out.println("Enter the students' grades");
grades[J] = input.nextDouble();
}
double best = grades[0];
for (int J = 1; J < number; J++) {
if (grades[J] >= best){
best = grades[J];
}
}
for (int J = 0;J < number; J++){
if (grades[J] >= best - 10){
System.out.println("Student " + J + " score is " + grades[J] +
" and grade is " + "A");
}
else if (grades[J] >= best - 20){
System.out.println("Student " + J + " score is " + grades[J] +
" and grade is " + "B");
}
else if (grades[J] >= best - 30) {
System.out.println("Student " + J + " score is " + grades[J] +
" and grade is " + "C");
}
else if (grades[J] >= best - 40) {
System.out.println("Student " + J + " score is " + grades[J] +
" and grade is " + "D");
}
else {
System.out.println("Student " + J + " score is " + grades[J] +
" and grade is " + "F");
}
} // end for loop for output
}// end main method
}
You're trying to access grades[number] in the first iteration of your outer for loop, but only 0 to number - 1 are legal
double[]grades = new double [number];
for (int J = number; J >=0; J--) {
System.out.println("Enter the students' grades");
grades[J] = input.nextDouble(); // trying to access grades[number] in first iteration
that could be easily fixed by changing your for loop to
for (int J = number - 1; J >=0; J--)
Remember, when you declare an array of size n it goes from 0.. to n-1
In your case, you can only go to grades[j-1]
for (int J =0; J < number; J++)
for (int J = number-1; J >=0; J--)
You can use either of one to solve this problem.

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}

Categories