I am working on a simple JAVA question in one of my college courses. I am stumped on this one program. I will display what I have so far and give the question I have to answer. I also looked at a similar question on StackOverflow, BUT it isn't the same problem so it DIDN'T help. The program I need to write is:
Write a program that uses 'while' loops to perform the following steps:
a.) Prompt the user to input two integers: 'firstNum' and 'secondNum' (firstNum must be less than secondNum)
b.) Output all the odd numbers between 'firstNum' and 'secondNum' inclusive.
c.) Output the sum of all the even numbers between 'firstNum' and 'secondNum' inclusive.
This is what I have so far... (I still need to calculate the even numbers and sum them up)
//import classes
import java.util.*;
public class chapter5no9
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
//Part A
int firstNum;
int secondNum;
int sumEven;
System.out.println("Please enter an integer: ");
firstNum = console.nextInt();
System.out.println("Please enter another integer less than the first integer: ");
secondNum = console.nextInt();
//Part B
if (firstNum < secondNum)
{
System.out.print("Your second number is greater than the first. So Please re-enter: ");
secondNum = console.nextInt();
}
else
{
System.out.print("Odd Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
System.out.println();
System.out.print("Sum of Even Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
}
}
}
I created the loopCounter variable to handle the required iterations without changing the values inputted by the user. The following changes have been made to your code.
Part A: added a while loop to validate user input. Also changed logic in if statement.
Part B: used one loop to print odd numbers and total even numbers
//Part A
int firstNum;
int secondNum;
int sumEven=0;
System.out.println("Please enter an integer: ");
firstNum = input.nextInt();
System.out.println("Please enter another integer less than the first integer: ");
secondNum = input.nextInt();
//Part B
//validate input in a loop
while(true)
{
if (firstNum > secondNum)
{
System.out.print("Your second number is larger than the first. So Please re-enter: ");
secondNum = input.nextInt();
}
else
{
break;
}
}
System.out.print("Odd Numbers: ");
int loopCounter=firstNum;
while(loopCounter<secondNum)
{
if (loopCounter%2!=0)
{
System.out.print(" " + loopCounter);
}//end if
else
{
sumEven+=loopCounter;
}//end else
loopCounter++;
}
System.out.println();
System.out.print("Sum of Even Numbers: ");
System.out.print(sumEven);
}
I would separate the two concerns of checking input and calculating the result. Here's how I would calculate it:
int sum = IntStream.rangeClosed(firstNum, secondNum).filter(i -> i % 2 == 0).sum();
The issue is in your logic. You have this if statement:
if (firstNum < secondNum)
{
System.out.print("Your second number is greater than the first. So Please re-enter: ");
secondNum = console.nextInt();
}
Which checks if the second number is greater than the first (which you want it to be) and then asks them to re-enter. You want to check if (secondNum < firstNum). You will need to reverse all your while and if statements that compare secondNum to firstNum.
Then you have this if (secondNum % 2 != 0) to check for odd numbers, which is correct, but you copy-pasted it to check for even numbers, which won't work, you will need to change that as well.
Then, you are outputting all the even integers inside your loop, when really you want to be adding it to an evenSum variable, and outputting that at the end of the loop:
System.out.println("The sum of all even integers is: " + evenSum);
That should be enough to help you, I'm not going to write your homework for you, that's not what we do here.
package hello.world;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number ;
int X = 0;
System.out.print("enter a number plz : ");
number = sc.nextInt();
while (X <= number){
System.out.println(X);
X ++;
}
}
}
Related
I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.
Create a NumberInTheRange application that prompts the user for two numbers.
The first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. Be sure to include the min and max numbers in the prompt.
I wrote a code allowing the users to write the two min and max values. However, I am wondering what code should I write in order to fulfill the conditions above. I am thinking about using loops and it would be very helpful if you guys correct me and give some instructions on how to process these.
import java.util.Scanner;
public class NumberinTheRange {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type two numbers:");
int n1=scan.nextInt();
int n2=scan.nextInt();
}
}
Use a do...while loop.
int num;
do {
System.out.println("Enter a number between " + n1 + " and " + n2 + ":");
num = scan.nextInt();
} while(num < n1 || num > n2);
Now, you need to put a condition to loop-back if the input is not in the range. You can use a do-while loop for the same. You can do it with any other loop but using a do-while loop guarantees that its body will be executed at least once.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Type two numbers: ");
int min = scan.nextInt();
int max = scan.nextInt();
int n;
do {
System.out.print("Enter a number in the range of " + min + "-" + max + ": ");
n = scan.nextInt();
} while (n < min || n > max);
System.out.println("Your number is: " + n);
}
}
A sample run:
Type two numbers: 10 20
Enter a number in the range of 10-20: 34
Enter a number in the range of 10-20: 5
Enter a number in the range of 10-20: 15
Your number is: 15
I wrote a code for school in java that verifies if a number is an armstrong number. I programmed it so that it runs as many times until the user inputs 0, at which the program will terminate. I am having 2 problems.
The code only works the first time through, if the user inputs 371 (an armstrong number) the first time, it works, but after that it returns that the number is not an armstrong number.
When the user inputs 0, it still shows the statement whether it is or is not an armstrong number, which I don't want it to.
This is the code:
import java.util.Scanner; //import Scanner for user input
public class Ch6Project {
public static void main(String[] args) {
int userNum, totalValue = 0, num, numLength; //declare variables that will be used
String suserNum; //declare user input variable
Scanner input = new Scanner(System.in); //declare a Scanner
System.out.println("Welcome to the Armstrong Number Program."); //description
System.out.println("\nTo calculate an Armstrong number: ");
System.out.println("\t 1. Cube each digit of the number.");
System.out.println("\t 2. Take the sum of these cubes.");
System.out.println("\t 3. If the sum equals the number, it is an Armstrong Number.");
System.out.println("\t e.g. 3^3 + 1^3 + 7^3 = 317");
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user input
userNum = Integer.parseInt(suserNum); //parse user input
numLength = suserNum.length(); //calculate length of user input
for (int i = numLength; i > 0; i--) { //create loop to run for n times
num = Integer.parseInt(suserNum.substring(numLength - 1, numLength)); //get last digit of number
totalValue += Math.pow(num, 3); //cube a digit
numLength--; //subtract userNum by 1 to get the rest of the digits
}
if (totalValue == userNum) { //if total value equals user input, it is Armstrong #
System.out.println("Your number is an Armstrong number.");
} else { //if total value does not equal user input, it is not an Armstrong #
System.out.println("Your number is not an Armstrong number.");
}
} while (userNum != 0); //run loop until user input == 0
input.close(); //close user input
}
}
Change your code so that it breaks immediately after entry of the userNum
e.g.
userNum = Integer.parseInt(suserNum); //parse user input
if (userNum == 0) {
break;
}
then you can also change your loop to a endless loop
while (true) {
// your code
}
It works only the first time because you don't reset your sum variable: just after the do insert:
do {
totalValue =0;..
}while (userNum != 0);
plus, your code doesn't immediatly exit because the check of the condition is at the end, hence you insert the number, the code is executed and THEN you check. BTW: when you can, avoid using break statement.
Put an if controll after the reading of the number, like this:
do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user inputuserNum =
Integer.parseInt(suserNum); //parse user input
if(userNum !=0){...your code...}
}while (userNum != 0);
There are a ton of more elegant way to code it but this should do the work
public class E1 {
public static void main(String[] args) {
int c = 0, a, temp;
int m = 153;
int n = m;
temp = n;
while (n > 0) {
a = n % 10;
n = n / 10;
c = c + (a * a * a);
}
if (temp == c)
System.out.println(m + " is an armstrong number");
else
System.out.println(m + "is not an armstrong number");
}
}
I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);
I am trying to get the average of user inputted numbers. Every time I input numbers the output is always-
The sum is 6
How many numbers: 4
Average: 2.0
A while loop is required, unfortunately for loops are not allowed. I am pretty new to Java so my formatting is sloppy. Where in my code are my problems?
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
You have several errors here.
The main one that causes your error is sum += count. Instead of adding what the user has entered, you are adding the number that shows how many numbers there are. So it will always add 0+1+2+3 etc.
Another problem is that, once you change the above, you have to check whether the input == endingVariable before you add the input to the sum. So you have to write the if first, and then calculate the average inside it. Otherwise it will treat your -1 as part of the sequence of numbers to calculate.
You only need to add the input to the sum and increment the count if you find out that the input is not yet the same as endingVariable.
So:
Add the input, not the count, to the sum.
Calculate the average only when you have reached the final item.
Add the input to the sum and increment the counter only if your input is not endingVariable.
Try this one...
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += input; // you were doing mistake here.
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
Two big issues with your code. First, this line:
sum += count;
It's probably just a typo, but it should be obviously:
sum += input;
Second, once you fix that, you will notice you are including the -1 in your sum. You probably want something like this:
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
if (input == endingVariable) {
average = (double) sum / count;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
} else {
sum += input;
count++;
}
Thank you for explaining in detail. It works fine now, all I had to do was what you said is change the input, and move the sum += input and count after the final item in an else. I was having the hardest time trying to figure out why my -1 was being included