print entered integer from input integer to integer - java

I am trying to obtain two integers as input, and then use these to output another list of integers, using the input as arguments in a loop.
In my code, if I enter low as 1, and high as 10 I expect my output should be the integers 1 through 10. However my code prints the value 1 ten times. I have tried different loops with no luck. Can someone please point out why my output is not as expected?
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the low number: ");
int low = input.nextInt();
System.out.print("Enter the high number: ");
int high = input.nextInt();
//int num1 = low
//int num2 = high
System.out.println("Decimal");
for(int i = low ; low <= high; low++)
System.out.println(i);
}
}

So the issue is that in your for loop you are incrementing the value of low with low++ but you're printing i which you only set to the value of low at the beginning; i doesn't get reset to the value of low on every iteration in your for loop.
So, try changing low++ to i++ and see if that makes a difference ;)
You'll also want to change low <= high to i <= high as we are now incrementing i.

Related

Array keeps counting 0 as a number when I didn'

I'm trying to make a game show program where I enter the number of contestants, how fast they hit the buzzer, the fastest and slowest times for hitting the buzzer, and the number of people that hit the buzzer faster than average.
Everything goes well with my program when I have 5 contestants. But if I enter 4 contestants or anything else less than 5, it messes up some things. When I have 4 contestants, my fastest time is 0, even when I'm not putting in a 0 as a time, and the number of contestants that hit the buzzer faster than average is also messed up, having one extra than it should, because it's putting in a 0.
How do I stop this program from adding in a 0 when I don't have 5 contestants?
import java.util.Scanner;
public class FastestFingers {
public static void main(String[] args) {
//declare varialbes
int contestants;
int [] milisecs = new int [6];
int fastest, slowest, i;
int faster = 0;
double average;
Scanner scanInt = new Scanner (System.in);
//make user enter number of contestants
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
//make user enter times
for(i=1;i<=contestants;i++)
{
System.out.println ("Time (ms): ");
milisecs[i] = scanInt.nextInt();
}
//calculate fastest time
fastest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] < fastest)
{
fastest = milisecs[i];
}
}
System.out.println ("Fastest: " + fastest);
//calculate slowest time
slowest = milisecs[1];
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i] > slowest)
{
slowest = milisecs[i];
}
}
System.out.println ("Slowest: " + slowest);
//tell program how to find average
int total = 0;
for(i=1;i<milisecs.length;i++)
{
total = total + milisecs[i];
}
average = total/contestants;
//find numbers faster than the average
int count = 0;
for(i=1;i<milisecs.length;i++)
{
if(milisecs[i]<average)
{
count++;
}
}
System.out.println ("Faster than average: " + count);
}
}
You create an int[] of fixed size 6. Then you compare the last 5 values to find the lowest. All int values are default 0. If you only set 4 values to anything larger than 0 the fifth value will always be 0 and therefore your lowest value.
You can fix this problem by setting the size of your array to the number of contestants.
Also remember that arrays start counting at 0 not at 1. Your loops should therefore be:
for(i=0;i<milisecs.length;i++), etc.
The problem is that you initialize the array to have six elements.
int [] milisecs = new int [6];
By default all of these values will be zero. Then in your loop you only initialize four of them, meaning that two will still be zero. Change your code to:
System.out.println ("Enter # of contestants: ");
contestants = scanInt.nextInt();
int [] milisecs = new int [contestants];
This will ensure that you will only have as many time slots as you have contestants.
Also array indexes start at zero, so you should change
fastest = milisecs[1];
to
fastest = milisecs[0];
And in your loops, start your variable at 0 instead of 1.
Array Index should start with 0. Please be careful with this. You code reads input and assigns to the milisecs starting from index 1.

Sorting evens and odds between the range of two integers using while loops?

NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.

Do-while statements beginner java max-min prompt

Hey guys I new to Java and on do-while statements, the question asks me to create a prompt that asks for a max and a min value, then it asks for another value between my max and min values. "The user should be continually be prompted until a number within the range is entered. Im having a hard time wrapping my head around using a do-while statement so some help would be nice thanks! Also try to keep it simple!
package Chapter6Java;
import java.util.Scanner;
public class Chapter6Prompter {
public static void main(String [] args){
int max, min, between;
Scanner input = new Scanner(System.in);
System.out.print("Enter a min value: ");
min = input.nextInt();
System.out.print("Enter a max value: ");
max = input.nextInt();
do {
System.out.print("Enter a value between your min and max values:");
between = input.nextInt();
} while (between != max && between != min);
}
}
Modify your condition in the while as:
while (between >= max || between <= min);
Since you are checking that between is in range you should check if its greater than or equal to minimum value and less than or equal to maximum value.
You want to repeat the loop if the number rentered in not in range
so condition will be - while (between > max || between < min);

Taking average of user input number

This is my code
import java.util.*;
import java.io.*;
public class eCheck10A
{
public static void main(String[] args)
{
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter your integers");
out.println("Negative = sentinel");
List<Integer> aList = new ArrayList<Integer>();
for (int n1 = in.nextInt(); n1 > 0; n1 = in.nextInt())
{
if(n1 < 0)
{
break;
}
}
}
}
if i want to take all the numbers that I enter for n1, and average them out, how do i refer to all these numbers? I am going to put them in the IF statement, so if a negative number is entered, the program stops and posts their average.
This is the pseudocode you need to do this task (pseudo-code since it looks suspiciously like homework/classwork and you'll become a better developer if you nut out the implementation yourself).
Because you don't need the numbers themselves to work out the average, there's no point in storing them. The average is defined as the sum of all numbers divided by their count, so that's all you need to remember. Something like this should suffice:
total = 0
count = 0
n1 = get_next_number()
while n1 >= 0:
total = total + n1
count = count + 1
n1 = get_next_number()
if count == 0:
print "No numbers were entered.
else:
print "Average is ", (total / count)
A couple of other points I'll mention. As it stands now, your for statement will exit at the first non-positive number (<= 0), making the if superfluous.
In addition, you probably want any zeros to be included in the average: the average of {1,2,3} = 2 is not the same as the average of {1,2,3,0,0,0} = 1.
You can do this in the for statement itself with something like:
for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
and then you don't need the if/break bit inside the loop at all, similar to my provided pseudo-code.
An outline of what you will need to do: Create a variable sum to add up all of the values and create another variable called count that will be used to store the number of non-negative numbers in your list, aList. Then divide the sum by the count to find the average.
Another way to do running average is:
new_average = old_average + (new_number - old_average ) / count
If you ever hit max for a variable type, you would appreciate this formula.

Categories