Java is setting Array sequence to 0 and not recognizing specific variables - java

I am doing a class in Computer Programming and right now we're using Arrays. My objective is to do the following:
~ Prompt users for how many math tests they have written this year.
~ Asks the users their score on each of these math tests.
~ Place each score in an array.
~ Sort the array and give their math scores from least to greatest.
~ Calculate an average of the math scores.
My problem occurs when it just only keeps the scores at 0 and later wont recognize the testGrade int variable so it won't average them.
Here is my full code as of right now:
public static void main(String... args) throws Exception
{
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
int testGrades = k.nextInt();
}
System.out.print("The original sequence is: \n ");
for (int i = 0;i < testResults.length; i++)
{
System.out.print(testResults [i] + ", ");
}
System.out.println();
SortEm(testResults);
System.out.print("The new sequence is : \n ");
for (int i=0; i < testResults.length; i++)
{
System.out.print (testResults[i] + ", ");
}
System.out.println();
for (int i = 0;i < testResults.length; i++)
{
System.out.println("The average of all your tests is " + (testGrades / testNum));
}
}
private static void SortEm (int [] ar)
{
int temp;
for (int i = ar.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (ar[j] > ar[j + 1])
{
temp = ar[j];
ar[j] = ar[j + 1];
ar[j+1] = temp;
}
}
}
}
I would really appreciate some insight on what's going on and how to fix it.
Thank you all in advance :)
My Errors after answer:
6 errors found:
File: C:\Users\herhstudent\Desktop\gg.java [line: 1]
Error: Syntax error on tokens, delete these tokens
File: C:\Users\herhstudent\Desktop\gg.java [line: 3]
Error: Syntax error on token "void", # expected
File: C:\Users\herhstudent\Desktop\gg.java [line: 3]
Error: Syntax error on token "...", . expected
File: C:\Users\herhstudent\Desktop\gg.java [line: 3]
Error: Syntax error on token "throws", interface expected
File: C:\Users\herhstudent\Desktop\gg.java [line: 6]
Error: Syntax error on token ";", { expected after this token
File: C:\Users\herhstudent\Desktop\gg.java [line: 44]
Error: Syntax error, insert "}" to complete InterfaceBody

Multiple problems here. The first is that testGrades is declared in the for-loop:
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
int testGrades = k.nextInt();
}
This means is has a narrower scope. It is not available later. You can move it to be declared before the for-loop but that still doesn't really make sense. This variable should represent the total score and we should be progressively incrementing it, not setting it every time. I've also renamed it so it's more obvious what it's doing:
int totalScore = 0;
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
totalScore += k.nextInt();
}
Now we need to address that you're never actually writing any values to the array. This loop now becomes:
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
testResults[i] = k.nextInt();
totalScore += testResults[i];
}
Finally, at the end we don't need to loop to print the average. We can just do it once. We don't need the variable testNum because we can just use testResults.length as you do previously.
System.out.println("The average of all your tests is " + (totalScore / testResults.length));
The final problem you'll run into is integer division. I'll leave you to solve that on your own.
Final code:
private static int[] testResults = new int[5];
public static void main(String... args) throws Exception
{
Scanner k = new Scanner(System.in);
int testGrades = 0;
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
testResults[i] = k.nextInt();
testGrades += testResults[i];
}
System.out.print("The original sequence is: \n ");
for (int i = 0;i < testResults.length; i++)
{
System.out.print(testResults [i] + ", ");
}
System.out.println();
SortEm(testResults);
System.out.print("The new sequence is : \n ");
for (int i=0; i < testResults.length; i++)
{
System.out.print (testResults[i] + ", ");
}
System.out.println();
System.out.println("The average of all your tests is " + (testGrades / testResults.length));
}
private static void SortEm (int [] ar)
{
int temp;
for (int i = ar.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (ar[j] > ar[j + 1])
{
temp = ar[j];
ar[j] = ar[j + 1];
ar[j+1] = temp;
}
}
}
}

Your program isn't recognizing your variables because you declare them inside loops. Variables that are declared inside of a loop do not exist outside of the loop. Try this:
int tesGrades = 0;
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
testGrades = k.nextInt();
}
Also the way you do this loop, testGrades keeps being overridden, and you won't have any input except the last. Try:
testResults[i] = k.nextInt();
Instead of:
testGrades = k.nextInt();
This will populate the testResults array with all the inputted test scores.

change first loop to this:
for (int i = 0;i < testResults.length; i++)
{
System.out.print("Thank you, now please enter your grade on each test: ");
testResults[i] = k.nextInt(); // <--
}

Related

String distorted when compile with online compiler "programiz" but fine with other compilers

I wrote a Tic-tac-toe program in Java, where the chess board's size is changable. When I tried to compile it at "programiz", an online compiler, the board got distorted.
Online Compiler #1
However, it works fine at my local compiler as well as at another online compiler(say "onlinegdb").
Local Compiler
Online Compiler #2
Below is the part of the code that print the board:
public static void printBoard(int size)
{
//create Strings of places to store moves
String [] symbolPlaces =new String[size*size];
//initialize the places
for(int i = 0;i < size*size; i++)
{
symbolPlaces[i]=" ";
}
//line 1
System.out.print(" ");
for(int i = 1; i <= size; i++)
{
System.out.print(i+" ");
}
System.out.println();
//create underscore line
String underscore = "";
for(int j = 1; j < size; j++)
{
underscore +="+---";
}
//rest of the lines
for(int i = 0; i < size; i++)
{
System.out.print((i+1)+" ");
for(int k =0; k< size-1; k++)
{
System.out.print(" "+symbolPlaces[i]+" |");
}
System.out.print(" "+symbolPlaces[size-1]);
System.out.println("");
if(i!=(size-1))
{
System.out.println(" "+"---"+underscore);
}
}
}
Does anyone has any idea why this could happen? Your advice would be much appreciated!

Array is printing each letter of a word on separate line, how to fix?

I'm currently working on an assignment for school and the objective is to have the user input n amount of lines and then print them in reverse.
For example:
"Please enter number of lines: "
3
"Please enter the lines: "
Hi
Hey
Howdy
Desired Output:
Howdy
Hey
Hi
My output:
H
o
w
d
y
H
e
y
H
i
I'm not sure what's wrong and I'd really like some help, here is my code:
import java.util.Scanner;
public class ReverseOrder {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the number of lines: ");
int numberOfLines = kb.nextInt() + 1;
String inputLines[] = new String[numberOfLines];
System.out.println("Please enter the lines: ");
for (int i = 0; i < numberOfLines; i++) {
inputLines[i] = kb.nextLine();
}
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
for (int j = 0; j <= inputLines[i].length() - 1; j++) {
System.out.println(inputLines[i].charAt(j));
}
}
kb.close();
}
You are printing each character with an end of line character by calling println() with your current two for loops. This is one step too many.
Since you already have the entire string, you can simply print the strings in reverse order like so using the println() function
for(int i = numberOfLines - 1 ; i>=0; i--){
System.out.println(inputLines[i]);
}
#Kody
I'm not sure what you have to do in your code but:
If you need just print each line in a reverse order, you can do this:
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
System.out.println(inputLines[i]);
}
The method println will create a new line for you.

Printing array elements with a for loop

This is a challenge question from my online textbook I can only get the numbers to prin forward... :(
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7
Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.
Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).
import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
for (i = 0; i < NUM_VALS; i++) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for (i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
Your two loops almost were correct. Try using this code:
for (int i=0; i < NUM_VALS; i++) {
// this if statement avoids printing a trailing space at the end.
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i]);
}
for (int i=NUM_VALS-1; i >= 0; i--) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i] + " ");
}
To print backwards you want:
for(i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");
I also have been working on the this textbook question. The issue with the above code is that i has already been assigned, so trying using int in the for loop will cause an error. Below is the code I used to successfully achieve the desired outcome.
for ( i = 0 ; i <NUM_VALS; ++i) {
if (i > 0) {
System.out.print("");
}
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for ( i = NUM_VALS -1; i >=0; --i) {
if (i > 0) {
System.out.print("");
}
System.out.print( courseGrades[i] + " ");
}
System.out.println();

Java Sorting Array

I have this code and I do not know why the selection sort is not sorting all the way Does anyone know where to fix the program. The selection sort code I believe is right i just dont know what is wrong. The code is functioning
import java.util.Scanner;
public class selectionSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int temp;
int i,j,first;
System.out.println("How many numbers do you want to enter?");
int ammount = scanner.nextInt();
int[]array = new int[ammount];
for (i = 0 ; i < array.length; i++ )
{
System.out.println("Enter the numbers now.");
array[i] = scanner.nextInt();
}
System.out.println("\nThe array is:");
for(i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
for (i=array.length - 1; i>0;i--)
{
first=0;
for(j=1;j<=1;j++)
{
if(array[j]<array[first])
first = j;
}
temp = array[first];
array[first] = array[i];
array[i]=temp;
}
System.out.println("\nThe sorted array is:");
for( i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
}
You appear to have a typo. This line:
for(j=1;j<=1;j++)
should probably be:
for(j=1;j<=i;j++)
(The loop termination test should be j<=i, not j<=1.)

Bubble sorting in Ascending - program won't compile

I need to write a program that uses a bubble sorting method and main function that asks for a user to input their array. After which the program sorts the array in ascending order. My program right now asks the for the user's input, but once that happens, the program won't compile and I'm stuck. Here's the code:
import java.util.Scanner;
public class IntSorter{
public static int bubbleSort(int[] a){
boolean needNextPass =true;
for(int i=1; i<a.length && needNextPass; i++){
needNextPass = false;
for(int j=0; j<a.length - i; j++){
if(a[j]> a[j+1]){
int temp = a[j];
a[j]=a[j+1];
a[j+1] = temp;
needNextPass = true;
}
}
}
for(int i=0; i<a.length; i++){
System.out.print(a[j] + " ");
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter size of array: ");
int N = input.nextInt();
int[] x = new int[N];
System.out.print("Enter " +N +"numbers of your array: ");
for(int i= 0; i<N; i++){
x[i] = input.nextInt()
}
IntSorter access = new IntSorter();
System.out.print("Your sorted array is: ");
access.IntSorter(x);}
}
You last line in your main method is : -
access.IntSorter(x);
Replace this line with: -
access.bubbleSort(x);
And using single uppercase character as variable is terrible.. use size instead for size of array..
System.out.print("Enter " +N +"numbers of your array: ");
for(int i= 0; i<N; i++){
x[i] = input.nextInt()
}
And in the above code, what if user didn't enter an integer value?? You will get an exception.. You need to catch that..
This line seems to be missing a semicolon:
x[i] = input.nextInt()
And you seem to be access a variable j outside of its scope:
System.out.print(a[j] + " ");
You could use i instead of j which is undefined:
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
Also
public static int bubbleSort(int[] a) {
has no int return value;
You can use your compiler or IDE to help highlight these issues.

Categories

Resources