The application should print the first n odd numbers, where n is between 1 and 25, starting at start. start is between 100 and 200 and it says where the odd number sequence should start. If start is an even number then the sequence should start at the next odd number.
Here is and example with n = 4 and start = 193:
193, 195, 197, 199
The application must allow the user to enter values for n and start. It must then verify that n is between 1 and 25 and start is between 100 and 200.
My code so far:
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
Scanner sc2= new Scanner(System.in);
int start = sc2.nextInt();
for (int i=start; i=n; i=start+1+=2)
if ((n>=1) && (n<=25)) {
System.out.println("Valid Input!");
}
else
System.out.println ("Invalid Input!!!");
if ((start>=100) && (start<=200)){
System.out.println ("Valid Input!");
}
else
System.out.println("Invalid Input!!!");
if (start%2==0) {
System.out.println ("Even Number Inputted! Next Odd Number displayed.");
}
}
It keeps telling me that int cannot be converted to boolean. I understand what it says just not sure how to rectify it.
First, prompt for the values
int minN = 1;
int maxN = 25;
int minStart = 100;
int maxStart = 200;
int start = getInput("Please enter starting value: ", minStart, maxStart);
int n = getInput("Please enter number of odd numbers to print: ", minN, maxN);
Now compute and print the results for start = 190 and n = 4
for (int i = start | 1; i <= maxStart && n-- > 0; i += 2) {
System.out.println(i);
}
prints
191
193
195
197
Explanation
First, the user is prompted for input using a method.
start - the starting point selected by the user
n - the number of values to generate also selected by the user
Then a loop is used to generate the values. This works by first, ensuring the start is odd by setting the low order bit to a 1. If the value is already odd, this has no effect. The loop begins with the first odd from start and increments by 2. The loop terminates if either i exceeds maxStart or n reaches 0.
The prompt method accepts a prompt message that is appropriate for the type of input. It also accepts a range to provide a helpful reprompt if the choice is out of range. As long as the user enters out of range values, the method will keep prompting. Otherwise, it returns the accepted value.
static Scanner input = new Scanner(System.in);
public static int getInput(String prompt, int min, int max) {
int value;
while (true) {
System.out.print(prompt);
if ((value = input.nextInt()) >= min && value <= max) {
break;
}
System.out.printf(
"Invalid entry, must be between %d and %d inclusive", min, max);
}
return value;
}
You only need one Scanner. You should perform input validation before your display loop. And your for loop syntax is incorrect, the second part should resolve to a boolean test (not an assignment) and i=start+1+=2 is just wrong. Fixing it might look something like
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.println("Print how many odd numbers (n)? Enter a value between 1 and 25.");
n = sc.nextInt();
} while (n < 1 || n > 25);
int start;
do {
System.out.println("Enter starting value? Enter a value between 100 and 200.");
start = sc.nextInt();
} while (start < 100 || start > 200);
if (start % 2 != 1) {
System.out.println("Even Number Inputted! Next Odd Number displayed.");
start++;
}
for (int i = start; i < start + (2 * n); i += 2) {
System.out.println(i);
}
The problem is in the for loop condition, you must change i=n into i<=n
This is my first time posting so bare with me.
I believe that the reason you are getting int cannot be converted to boolean is because in your for loop, the second statement says i=n. This statement of the for loop needs to be a logic block.
I am a firm believer in giving resources rather than the answer, so check out this write up done by w3schools (killer resource btw) on for loops in java: https://www.w3schools.com/java/java_for_loop.asp
I believe problem is for loop at the condition part, i cannot be equal n like i=n. You can change it i<=n
Related
I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4
The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)
I am very new to coding and Java. I have the following assignment: Write a program that reads a couple of positive numbers from the input and computes and prints the average, with 3 decimals precision. The input list closes with the number -1.
So I have a working program, however I have no clue how to integrate the condition 'print the average with 3 decimals precision'. Do you have any idea how to fix this? Many thanks!
See my code below:
import java.util.Scanner;
public class Parta {
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter -1 to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum == -1)
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
else
{
sum += negNum;
count++;
avg = sum/count;
}
}
}
}
You just have to break out of the loop for your -1 condition.
while(1) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n == -1)
break;
}
Change
for(int i=0; i < numbers.length + 1= -1 ; i++)
to
for(int i=0; i < n ; i++)
The
%n
is out of place in the print statement also. I'd remove that.
To implement your -1 condition, check for a == -1 in the for loop:
if (a == -1) {break;}
The input list closes with the number -1.
I assume this means that -1 is the final number you are looking for and when read then all inputs are then completed? You just need a condition to check if the number you are looking at is -1, if it is then stop reading.
Your code does not meet your requirements.
The first requirement is that you have to calculate fractions. But you stick to int as type of your variables. As written by #nbokmans your variables should be of type double or float.
The other problem is that your code takes the first number given as the count of the numbers to follow. But you're told to use any number for calculation until input is -1. You cannot do this with a for loop, you need a while loop for this.
An the easiest way to accomplish your task is to calculate the result on the fly while getting the input:
pseudo code:
declare sum as double initially 0.0;
while(input is not -1)
sum = (sum + input) / 2;
output sum:
I am trying to find the even sum and even max from numbers inputted by the user. For example, if they answered "How many integers?" with 4 and inputted the integers: 2, 9, 18, 4 it should output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
Here is my code:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
//prompt user to enter the first integer
System.out.print("next integer? ");
int firstNum = console.nextInt();
//set the even max to the firstNum
int evenMax = firstNum;
//set the evenSum to zero
int evenSum = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 2; i <= numbers; i++) {
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the first number is even
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
//check to see if the numbers entered are even
if (num % 2 == 0) {
//if they are even add them to the evenSum
evenSum += num;
}
//check to see if the number entered is bigger than the first number
if (num > firstNum) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
But here is what is my output is:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 28
even max = 4
Could someone help me figure out what the problem is?
You were doing some really weird stuff where the first time a number was entered it was treated as special. This was causing the first even number entered (2, in this case) to be added multiple times to the total.
Put all of your input in the same loop so you can treat everything equally:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
int evenSum = 0;
int evenMax = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 0; i < numbers; i++) {
//input new number
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the number is even. if it is not even,
//we don't care about it at all and just go to the next one
if (num % 2 == 0){
//add it to the sum
evenSum += num;
//if it's larger than the maximum, set the new maximum
if (num > evenMax) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
As you can see, this code also only checks to see if a number is even once. There is no need to be continuously checking if num is even every time you use it: its value is not changing during the duration of a single run of the loop.
Move the following code inside the for loop to just before the for loop-
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
This will prevent the repeated addition of the first number in the evenSum
You also want
if (num > evenMax) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
or, alternatively
if (num > evenMax && num % 2 == 0) {
evenMax = num;
}
In your scenario, firstNum is 2 so every number after it is technically larger, so you will (theoretically) not get the largest even number entered after the first number.
Either move the first if condition inside the for loop upwards (outside of the for loop)
or store all of the user inputs in a data structure i.e. Array before processing them.
Storing them in Array would make it easier to manipulate the data.
Working code:-
Scanner console = new Scanner(System.in);
int numbers =0, firstNum =0, num =0 ;
System.out.print("how many integers? ");
numbers = console.nextInt();
System.out.print("next integer? ");
firstNum = console.nextInt();
int evenMax = 0;
int evenSum = 0;
if(firstNum%2==0)
{
evenSum = firstNum;
evenMax = firstNum;
}
for (int i = 1; i < numbers; i++) {
System.out.print("next integer? ");
num = console.nextInt();
if (num % 2 == 0) {
//don't add firstNum multiple times to the evenSum, earlier it was added every time you entered an even number
evenSum += num;
//check if the number you entered, i.e. num greater than the already existing greatest number i.e. evenMax and if so update it
evenMax = num > evenMax: num?evenMax;
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
Hope this helps. There are three major problems in your code:-
The firstNum(if it's even) gets added to the sum every time you enter a even number. i.e. if first number is 4 and the loop runs 10 times and encounter 6 even numbers, then along with the even number 4 also gets added six times. If you want to use it as a special number and get it's value separately then you'll have to add it to the sum before the loop.
You should compare every new even number to the previous greatest even number and hence set the value of evenMax. You are comparing them to the firstNum so if the first number is 2 and the last even number is anything greater than two, it would be set as the value of evenMax. Compare every even number to the current maximum even number i.e current value of evenMax.
You don't check if the first number is evenor not and assign it to even max. So if it is 999999 it still get's assigned, but it is not even.
Please check it as correct answer and vote up if you find it useful.
I am writing a Babylonian algorithm for computing the square root of a positive number, and the iteration should keep going until the guess is within 1% of the previous guess.
the code that I have written gets the iteration going to the one before error is 1%. how can I make it to do one more iteration ?
to get the question straight, is there a way to tell it iterate untill the error is <1% ?
import java.util.Scanner;
public class sqrt {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("\nplease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
if (num>=0){
guess = num/2;
do{
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error<0){
error = -error;
}
}
while(error>0.01);
System.out.println("The square root of the number " + num +" is equal to " +guess);
} else {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
}
}
Add a new counter that only gets increased in the (former) exit loop condition.
int exit = 0;
do {
...
if (error <= 0.01) {
exit++;
}
} while (exit < 2);
If you want to return a value only when the error is strictly less than 1%, you need to change the while condition.
Changing it to error >= 0.01 says "iterate, even when error is exactly equal to 1%, so we get a final error less than 1%".
Also, your if (num <= 0) allows a division by zero to happen, when num is exactly zero.
Let's check:
num = 0;
guess = num / 2; // guess = 0
r = num / guess; // r = 0 / 0
Looking at the below code should give you a clearer idea. I've commented it.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("\nPlease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
// Previous code allowed a division by zero to happen.
// You may return immediately when it's zero.
// Besides, you ask clearly for a *positive* number.
// You should check firstly if the input is invalid.
if (num < 0) {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
// Since you assigned guess to zero, which is the sqrt of zero,
// you only have to guess when it's strictly positive.
if (num > 0) {
guess = num/2;
// Notice the slight change in the while condition.
do {
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error < 0) {
error = -error;
}
} while(error >= 0.01);
}
// Finally, print the result.
System.out.println(
"The square root of the number " + num +
" is equal to " + guess
);
}