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();
Related
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(); // <--
}
This is my first question, so sorry if I'm not clear
So I'm trying to write a void function printReverse that prints a reversed array and skips every other element in the process. This is what I have:
void printReverse(int[] array) {
for(int i = 0; i < array.length / 2; i+=2){
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
while(i < array.length){
println(array[i]);
i++;
}
}
}
Say that I had an array of {10, 20, 30, 40, 50, 60}, I'm trying to print out on different lines (println) 60 40 20
How would I do that with the code so far?
You can also start from the end of the array, it really easy to do this like that:
for(int i=array.length-1; i>=0; i=i-2)
System.out.println(array[i]);
notice that i=array.length-1 as if array.length is 3 for example, the last index will be 2. Also notice that i>=0 as i is initialize to the end of the array and 0 is the first index of the array.
Here you go:
int[] array = new int[] { 1, 2, 3, 4 };
int count = 0;
for (int i = array.length - 1; i >= 0; i--) {
if (count++ % 2 != 0) {
continue;
}
System.out.println(array[i]);
}
Besides having the system just print it, you could use a for loop to do this.
So,
for (int i = 6, i > array.length, i - 2)
{
System.out.println(array[i]);
}
Which would print out every other element in reverse order, given that there are 6 elements in the array. Of course, you could have a variable set to the length of the array, and plug in the variable instead of six, but this is just an example.
Hope this helps!
Check Image for Output Here you go in simple way,Thank you!!
import java.util.Arrays;
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter total number of elemets: ");
int total = sc.nextInt();
int[]arr1 = new int[total];
int[]arr2 = new int[total];
System.out.print("Enter elemets: ");
for(int i = 0; i<total; i++)
{
arr1[i]= sc.nextInt();
}
System.out.print("Original Array: " +Arrays.toString(arr1));
System.out.println();
for(int a = 0 ; a< total; a++)
{
for(int j =total-a-1; j>=0; j--)
{
arr2[a]= arr1[j];
break;
}
}
System.out.print("Reversed Array: " +Arrays.toString(arr2));
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
How do I print what is stored in the array in an easy way. I have been staring at this for the past 3 hours!
import java.util.Scanner;
public class December2012 {
public static void main(String[] args) {
int[] array = new int[100];
int sum = 0;
int i = 0;
Scanner input = new Scanner(System.in);
while (sum <= 100 && i < array.length) {
System.out.print("Write in the " + (i + 1) + "th number: ");
array[i] = input.nextInt();
sum += array[i];
i++;
}
System.out.print("You added: ");
System.out.print(array[i] + " ");
System.out.println("\nsum is " + sum);
}
}
The easiest way is
System.out.println(Arrays.toString(array));
Just for the record you could also use the new for-each loop
for(int no : array ) {
System.out.println(no);
}
you can do like this
for(int j= 0 ; j<array.length;j++) {
System.out.println(array[j]);
}
or
for (int j: array) {
System.out.println(j);
}
for (int i = 0 ; i < array.length; i++){
System.out.println("Value "+i+"="+array[i]);
}
thats all my friend :)
I did an exercise in one of my books to get this output. We are supposed to use nested loops and basic java. I could not format the output in here but the code below produces the correct output. I got it to print the correct output but I feel like it is very redundant, mainly with the loops regarding the * and spaces if you have a better method for doing this please share!
private static void printDesign(){
int astrickStopper = 1;
int slashStopper = 1;
for (int lines = 1; lines <= 7; lines++) {
for (int firstAstrick = 6; firstAstrick >= astrickStopper; firstAstrick--) {
System.out.print("*");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int forwardSlash = 6; forwardSlash >= slashStopper; forwardSlash--) {
System.out.print("//");
}
for (int backSlash = 1; backSlash < slashStopper ; backSlash++) {
System.out.print("\\\\");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int secondAstrick = 6; secondAstrick >= astrickStopper; secondAstrick--) {
System.out.print("*");
}
astrickStopper = astrickStopper + 1;
slashStopper = slashStopper + 1;
System.out.println();
}
}
The code you wrote seems like it meets the problem description. You could move the inner loop into a function that outputs a given sequence of characters a certain number of times, then you would just be calling the function 6 times instead of having 6 inner loops.
public void printChars(int count, String chars) {
for (int i = 0; i < count; i++) {
System.out.print(chars);
}
}
I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}