I am trying to get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers?
At the end it should look like this:
Entered value: 20
Sum of even numbers between 2 and 20: 110
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int i = 2;
while (i <= value)
{
if (i%2 == 0){
text = (text + i);
if (i< value)
text = (text + ", ");
else
text = (text + ". ");
}
i++;
}
//Output
System.out.println(text);
}
}
}
Edit:
Final answer:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int sum = 0;
for (int i = 2; i <= value; i +=2){
sum += i;
}
//Output
System.out.print(text);
System.out.println(sum);
}
}
}
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness.
int sum = 0;
for (int i = 2; i < value; i+=2) {
sum += i;
}
System.out.println(sum);
On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.
Related
The output should look like the attached screenshot. I am stuck on the very last step. Using a for loop to call the getCharacter method 10 times and converting the characters to a string using the Character.toString() method.
``
public static void main(String[] args) {
int count = countNumbers();
countPlay(count);
String word = getCharacter();
stringOf10(word);
}
public static double getRealNumber(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a real number, one that has a decimal point: ");
double realNumber = sc.nextDouble();
return realNumber;
}
public static int countNumbers(){
int count = 0;
do{
if (getRealNumber() == -1.0)
break;
count++;
} while(true);
System.out.println("The count is " + count);
return count;
}
public static int countPlay(int count){
int exponent = 4;
double result = 0;
result = Math.pow(count, exponent);
System.out.println(count + "^" + exponent + " is " + result );
return count;
}
public static char getCharacter(){
Scanner input = new Scanner(System.in);
System.out.println("You will be asked to enter 10 characters.");
System.out.print("Enter a character: ");
char character = input.next().charAt(0);
return character;
}
public static char stringOf10(String word){
char i = getCharacter();
i = Character.toString(word) ;
for (i = 0; i < 10; i++){
}
return word;
}
}
``
Consider the following block of code which will run in the main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = "";
//Print the instructions before the loop
System.out.println("You will be asked to enter 10 characters.");
//request characters inside the loop
for (int i = 0; i < 10; i++){
System.out.print("Enter a character: ");
word += input.next().charAt(0);
}
//print the result (or return from a method)
System.out.println("The word is: " + word);
//return word;
}
Besides the corrections in comments, note how we create a local variable word, and simply update/append that inside the for loop word += input.next().charAt(0);.
You can easily move this code to fit your needs and return the value to be printed:
public static void main(String[] args) {
//Call the method to get our word and save the result
String result = stringOf10();
//Print the result
System.out.println("The word is: " + result);
}
public static String stringOf10(){
//Creater a scanner once before the loop
Scanner input = new Scanner(System.in);
//Create a local variable to store the word as it is updated
String word = "";
//Print the instructions once before the loop
System.out.println("You will be asked to enter 10 characters.");
//Create a loop that will run 10 times "for (int i = 0; i < 10; i++)"
//The loop starts by creating an int that is 0 "int i=0"
//Each time the loop ends it will do "i = i+1"
//The loop will run until i is no longer less than 10 "i < 10"
//Once that happens the loop will end and the code after the loop will run
for (int i = 0; i < 10; i++){
//Dach time the loop will call this method and update the word
word += getCharacter(input);
}
return word;
}
public static char getCharacter(Scanner input){
//Each time this method is called we prompt the user to enter a character
System.out.print("Enter a character: ");
//We then return the character to the previous method
return input.next().charAt(0);
}
so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}
Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.
I want my program that to accept user number input and output the sum from 1 up to the input number (using while loop).
Example: If input value is 4, the sum is 10 i.e., 1 + 2 + 3 + 4.
My code compiles but returns a never ending 1 until my jcreator stops responding.
import java.util.Scanner;
import java.io.*;
public class SumLoopWhile {
public static void main(String[] args) {
int number;
int sum = 1;
Scanner in = new Scanner (System.in);
System.out.println("Enter number: ");
number = in.nextInt();
while (sum <= 10) {
System.out.println("Sum is: " + sum);
number++;
}
}
}
You should be comparing the value to the number that was input, and adding to the sum. Finally, display the result after the loop. Something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int number = in.nextInt();
int sum = 0;
int v = 0;
while (v <= number) {
sum += v;
v++;
}
System.out.println("Sum is: " + sum);
}
Which will print Sum is: 10 when the input is 4 (as requested).
I guess that what you want it's to modify the sum inside your while loop. Do it like this:
while (sum <= 10) {
sum = sum + number;
number++;
}
}
System.out.println("Sum is: " + sum);
You have to put your System.out.println out of the loop because you want to print the total value, not each sum that it's calculated in each iteration.
Also, it should be nice that when you want to initialize some int that will be a "total" variable (like the result of a sum, rest or whatever), initialize it to zero.
int sum = 0;
Your output variable sum is having the same value throughout the program.it is not getting altered.the while loop becomes infinite loop
The Condition
(sum <= 10) never becomes true and the while loop will run for infinite times
import javax.swing.JOptionPane;
public class SumUsingWhileLoop {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Input the number:");
int number;
number = Integer.parseInt(input);
int sum = 0;
int i = 1;
while (i <= number) {
sum += i;
i++;
}
JOptionPane.showMessageDialog(null, "Sum = " + sum);
System.exit(0);
}
}
The System.out.println should not be placed inside the while loop, because it will get executed as many times as the loop.If you want to print the sum value only once, then the statement System.out.println must be placed outside the loop block.
Just use another variable for counting the iterations.For example
while(count<=number)
{
sum=sum+count;
count++
}
System.out.println("Sum is: "+ sum);
I've created this code to get unlimited values of integers, store them, and calculate the mean. It also does it in a squared format. My problem is, I created it so that the while loop only stops when the the number 0 is entered. However, I only put it there as a substitute, as it's the only way i could test the rest of the code to ensure it all works.
What I really want to do it have the while loop continue until the user provides input that is not an integer. Ive tried everything, using hasNextint() or nextint and so forth, what can I do?
import java.io.*;
import java.util.*;
public class InputStats {
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
int inputNumber; // One of the integers input by the user.
int sum; // The sum of all the integers.
int count; // The number of integers that have been entered.
double mean; // The mean value of the integers, rounded to 2 decimal places.
int squarein; // Value of squared number.
int sumsquare; // The sum of the squares of all the integers.
double meansquare; // The mean value of the squares of integers, rounded to 2 decimal places.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
/* Read and process the user's input. */
System.out.println("Enter your first positive integer: ");
inputNumber = TextIO.nextInt();
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
squarein = inputNumber; //
sumsquare = squarein * squarein; //square inputs
count++; // Count the input by adding 1 to count.
System.out.println("Enter your next positive integer, or 0 to end: ");
inputNumber = TextIO.nextInt();
}
/* Display the result. */
if (count == 0) {
System.out.println("You didn't enter any data!");
} else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
You should read your values in as a string and then convert them to integers with Integer.parseInt(string);
That way you can use the following function to check if they're integers
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Your program would then look like this:
import java.io.*;
import java.util.*;
public class InputStats {
// *** I added this to help your while loop ***
public static boolean isInteger(String s) {
// check if a string is an integer, eg "10" is 10 but "w" is not an int
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
// *** I added this to store the input as a string first ***
String input; // The original string inputted by the user
int inputNumber;
int sum;
int count;
double mean;
int squarein;
int sumsquare;
double meansquare;
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
System.out.println("Enter your first positive integer: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
// *** I made this while it's an integer so it stops when it's a string ***
while (isInteger(input)) {
inputNumber = Integer.parseInt(input);
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein * squarein;
count++;
System.out.println("Enter your next positive integer, or a non integer to end: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
}
if (count == 0) {
System.out.println("You didn't enter any data!");
}
else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
// *** I removed this because it was no longer needed *** TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
hasNextInt() should work
while(TextIO.hasNextInt()) {
inputNumber = TextIO.nextInt();
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein*squarein;
count++;
System.out.println("Enter your next positive integer: ");
}
Another thing, why do you call TextIO.nextInt() before your System.outs? It doesn't seem necessary and could possibly throw an error.
Use a boolean flag. Set it to false initially and when user has inputted set it to true.
boolean userInputted = false;
while (!userInputted) {
.
.
.
// if user has inputted
userInputted = true;
}
You could have the user input one line of text with numbers separated by commas and use .split(",") to separate into an array of strings, then loop through that array by the .length and apply .trim() to each string to remove trailing space, then use Integer.parseInt(strarray[i]) to convert the strings to integers. And obviously put it all in a try...catch in case the user inputs badly formatted data.
What you need is a way to tell if what the user inputs is a number or something else.
Try something like this function.
//Function to parse the input from provided scanner, and return null
//if input is not a number
public static Integer parsedInputFrom(Scanner sc){
String input= sc.next();
Integer inputNumber=null;
try{
inputNumber = Integer.parseInt(input);
} catch (NumberFormatException n){
return null;
}
return inputNumber;
}