how would I find the nth term in a loop? java - java

Here is a quick look at the program that I made to give a better example of my question.
Loop code
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
This is what my program outputs
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44
This work can be up to 4 days late before failing.
This is what the output is supposed to be
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24
This work can be up to 4 days late before failing.
I have to display how many days late the assignment is and calculate the late penaltie (mark -5) I also have to display the number of days needed needed to fail the assigment ( number of days until failure might be larger than the number (d) of days that the user input ) . the failing mark is less than 40.
2nd example (output)
Please input mark: 64
Please input number of days to display: 2
Scheme 1
(0) 64 (1) 59 (2) 54
This work can be up to 4 days late before failing.
I have almost complete my code but this problem is slowing me down.
P.S. I am new at java
here is my full program
LatePenalties calss
public class LatePenalties {
// attributes
private int mark;
private static final int constantDiffSch1 = -5;
private static final double constantDiffSch2 = 0.9;
private static final int START_CONDITION = 0;
// constructors
public LatePenalties(int m) {
mark = m;
}
// methods
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
public void scheme2(int d) {
double total = mark;
System.out.print("\n\nScheme 2"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print( "(" + loopParameter + ") " );
System.out.printf("%.02f",total);
System.out.print(" ");
total = total * constantDiffSch2;
} // End
System.out.print("\n");
}
}
Main class
import java.util.Scanner;
public class LatePenaltiesUser {
public static void main(String [] args) {
// local variables
Scanner input = new Scanner(System.in);
LatePenalties latePen;
int mark;
int days;
// input
do{
System.out.print("Please input mark (between 0 and 100) --> ");
mark = input.nextInt();
if (( mark < 0 ) | (mark > 100 )){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while(( mark < 0 ) | (mark > 100 ));
do{
System.out.print("Please input number of days to display (between 0 and 20) --> ");
days = input.nextInt();
System.out.print("\n");
if (( days < 0 ) | (days > 20 )){System.out.print("Input value outside the range!!!"+ "\n");}
}while(( days < 0 ) | (days > 20 ));
// computation
latePen = new LatePenalties(mark);
latePen.scheme1(days);
latePen.scheme2(days);
}
}
I have to show when the faling mark occurs(at less than 40), but I have to stop the loop at 20 or when the number of days is reached, as I show in the example on what it is expected.

You can use break to come out of the loop as soon as total is less than 40. You can update your scheme1 method as below
public void scheme1(int d) {
int total = mark;
System.out.print("Scheme 1" + "\n");
int days = 0;
// Loop
for (int loopParameter = START_CONDITION; loopParameter <= d; loopParameter++) {
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
if(total < 40)
break;
days++;
} // End
if (total <= 40) {
System.out.print("\nThis work can be up to " + days +" days late before failing.");
}
System.out.print("\n\n");
}
Please input mark (between 0 and 100) --> 82
Please input number of days to display (between 0 and 20) --> 10
Scheme 1 (0) 82 (1) 77 (2) 72 (3) 67 (4) 62 (5) 57 (6) 52
(7) 47 (8) 42
This work can be up to 8 days late before failing.

You don't need to know your loopParameter to calculate the number of days. You can calculate it like so:
int days = (d - 40) / -constantDiffSch1;
You can use break when you want to quit loop. So:
if (total < 20) break;
And off topic. Don't call loopParameter like that. It is good practice to call it in one symbol (or short word) like i or day. It makes code easier to read and understand.

Related

Finding middle of user input (int) and increasing/decreasing half of the values in JAVA

Im trying to implement a program in Java that a user inputs a number greater than 10 & another number (whatever number) then it will list whatever first number the user inputs for example if it was 11 then it'd print 1-11 with corresponding numbers in which it increases by 50 in the first half (1-6) and decreases 25 for the rest (7-11). I have the following code but im having trouble trying to figure out the logic/how to go about the values being increased/decreased.
again the output would be something like this:
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
import java.util.Scanner;
public class Periods2
{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("enter the number of days in a given period:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
if(number < 10){
System.out.print("the number of days doesnt meet the required criteria enter it again:");
number = reader.nextInt();
}
System.out.print("enter the number of sharepoints:");
int sharepoints = Integer.parseInt(reader.nextLine());
while (numbers <= number && sharepoints > number){
System.out.println(numbers + " " + sharepoints);
numbers++;
}
}
}
Find the half of your input, and in your loop you can add 50 to sharepoints until the value of numbers reaches half, and then decrease by 25 after that:
int half = (int) Math.ceil(number/2.0);
while (numbers <= number && sharepoints > number){
System.out.println(numbers + " " + sharepoints);
if(numbers < half) {
sharepoints += 50;
}
else {
sharepoints -= 25;
}
numbers++;
}

Need first output to be a number, but its that numbers concatenation

My code is as follows:
import java.util.Scanner;
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;
int sharePoints;
Scanner keyboard = new Scanner(System.in);
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
System.out.print("Share points on the first day: ");
sharePoints = keyboard.nextInt();
while (numberofDays < 10 || numberofDays > 20) {
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
}
System.out.println("Day " + " Share Points");
for (int i = 1; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
}
}
}
}
This code should output to something like (as an example if the user were to enter the values 11 for the day and 550 for share price):
Day Share Points
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
however when I enter 11 for the day, and 550 for the share price, my code looks like:
Day Share Points
1 600
2 650
3 700
4 750
5 800
6 850
7 825
8 800
9 775
10 750
11 725
From what I can tell according to my code, I have coded it so that it adds 50 every time until the number six- whereas I want it to display the first number as the user enters it in, then to start adding and subtracting accordingly (note that everything is as I want it in my output except for the first number, and the proceeding numbers, as a result, being different). My wording may not be very accurate, but I hope the example outputs are enough to explain what I want as my output.
Sometimes it can be useful to process a base case before a for loop.
In your case that would look like printing the appropriate line for day 1 and then starting your loop at i=2 instead of i=1.

Java basic average number and random number

I was just practicing java programming by myself using random and averaging numbers but I was having a difficult time to do it. The program will ask "Enter # to be rolled between 0 to 100". Then I enter '3' then the output will be random 3 numbers.
My question is after 3 numbers come out, I want to find the average of those numbers. For example, I want my output to be
Your # is 89
Your # is 50
Your # is 12
Your avg is ##(//whatever the avg of numbers)
My output is like
Enter # to be rolled between 0 to 100
3
Your # is 89
your avg is 29
Your # is 39
your avg is 13
Your # is 76
your avg is 25
Can you guys help me to solve this problem? I know my codes are mess.
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran;
System.out.println("Enter # to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}
You need to define avg outside of the loop and then add all your numbers to it. It's also better to call it sum and define it as double to prevent rounding, this way you can divide it by number after the loop and get the average.
double sum = 0;
for(int i=0; i<number; i++) {
// ...
sum += ran;
}
System.out.println("your avg is " + sum/number);
int sum=0;
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
sum = sum+ran;
}
System.out.println("your avg is " + sum/number);
it's tested :
user must enter a number integer :
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran = 0;
System.out.println("Enter A NUMBER to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ran+(ranNumber.nextInt(100));
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}
output :
run:
Enter A NUMBER to be rolled between 0 to 100
5
Your # is 95
your avg is 19
Your # is 107
your avg is 21
Your # is 178
your avg is 35
Your # is 274
your avg is 54
Your # is 338
your avg is 67
BUILD SUCCESSFUL (total time: 2 seconds)
You want the compute the average only once, outside the loop, after the loop generates the values. You could accomplish your goal as follows:
Intialize an accumulator variable to zero before the loop
Inside the loop, add each generated value to the accumulator
After the loop, divide the accumulator value by the number of values
If you just want the average, define a variable that keeps the accumulate total, and then divide by the number of rolls.
// double for large values and decimal division later on
double total= 0;
int rolls = 4;
for ( int x = 0 ; x < rolls; x++ ) {
total += x;
}
// calculate average
double average = total / rolls;
// validate that it works, ( ( 0 + 1 + 2 + 3 ) / 4 ) == 1.5
Assert.assertEquals( 1.5d, average );

Make range with only first and last number? Java?

I have to get input for a certain number of days and a starting number. With that, the number of days gets split in half, in first half starting number decremented by 2. Last half incremented by 1. If days is uneven, last half has one more day. Heres what I have:
int days;
int num;
int 1half;
int 2half;
int new_num;
System.out.print("Enter number of days: ");
days = keyboard.nextInt();
System.out.print("Enter number of first day: ");
num = keyboard.nextInt();
int half = days/2;
if (days %2 == 0){
1half = (half);
2half = (half);
} else {
1half = (half);
2half = (half) + 1;
}
int first_half[] = {1,(half)};
int last_half[] = {((half)+1), days};
while (1half > 1 || 1half < half) {
new_temp = temp - 2;
System.out.println("Day \t Num");
System.out.println(new_num);
first_half--;
}
while(2half >= (half + 1) && (2half <= days)) {
new_temp = temp++;
System.out.println("Day \t Num");
System.out.println(new_num);
last_half--;
}
Im stuck now though.
If you see anything Id be happy to hear about it. I just need some help/advice. I'll clarify anything if this is hard to understand. Thank you in advance
Edit:
The final output should look something like this:
Day Num
1 -10
2 -12
3 -14
4 -16
5 -18
6 -17
7 -16
8 -15
9 -14
10 -13
11 -12
If this makes sense.
Heres my output:
Day Temperature
8
Day Temperature
8
Day Temperature
8
Day Temperature
continues forever
I don't know why do you need those arrays and other stuff, but you may have a look at my code. It produces exactly what you want.
int days = 11;
int num = -10;
int output = num + 2;
System.out.println("Day \t Num");
int half = days / 2;
for (int i = 1; i <= half; i++) {
output -= 2;
System.out.println(i + "\t" + output);
}
for (int i = half + 1; i <= days; i++) {
output++;
System.out.println(i + "\t" + output);
}
Your endless loop is caused by your condition statement of your while:
while (1half > 1 || 1half < half).
If 1half is set to be any number greater than 1 then this will loop forever. You probably want to use an && instead of an || as well. But don't see anything in the body of the loop that would affect things to make it get out of the loop.

Guessing game - how to remember the guessing range

I'm trying to make a simple guessing game where computer should guess the number I chose between 0 and 100. Try to run it, press 1 if the number is too low and press 2 if the number is too high.
1.if I choose 50 and computer guesses 41, I press 1 because the number is too low
2.then computer guesses between 41 and 100, say 70, I press 2 because it's too high
3.now the problem is that next the computer should be guessing between 70 and 41 (previously guessed number), but it guesses between 71 and 0, so it's jumping up and down all the time between extremes
4.I don't know how to make it remember the range ie. previously guessed number
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num=input.nextInt();
int ans=0;
Random rand = new Random();
int guess=rand.nextInt(100);
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
guess=rand.nextInt(100-guess+1)+guess;
}
else if (ans==2) {
guess=rand.nextInt(100-guess+1)+0;
}
}
System.out.print("Computer guessed: " + guess);
The output looks like this:
Enter a number: 50
Is it 55 ? 2
Is it 26 ? 1
Is it 35 ? 1
Is it 44 ? 1
Is it 54 ? 2
Is it 31 ? 1
Is it 39 ? 1
Is it 87 ? 2
Is it 0 ? 1
Is it 11 ? 1
Is it 97 ? 2
You should use 2 variables: One for upper limit, one for lower limit.
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
lowerLimit = guess; // Your new lower limit .
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
else if (ans==2) {
upperLimit = guess; // Your new upper limit.
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
}
This is what you need :
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int ans = 0;
Random rand = new Random();
int min = 0;
int max = 100;
int guess = rand.nextInt(max);
while (guess != num) {
System.out.print("Is it " + guess + " ? ");
ans = input.nextInt();
if (ans == 1) {
min = guess + 1;
} else if (ans == 2) {
max = guess;
}
guess = rand.nextInt(max - min) + min;
}
System.out.print("Computer guessed: " + guess);
sample output:
Enter a number: 50
Is it 62 ? 2
Is it 39 ? 1
Is it 41 ? 1
Is it 56 ? 2
Is it 54 ? 2
Is it 49 ? 1
Is it 52 ? 2
Computer guessed: 50
You need two variables. One for the lower limit and one for the upper limit.

Categories

Resources