I am trying to limit the input number to be greater than 0 and an integer.
Code Here:
import java.util.Scanner;
public class PROB4_CHAL1 // Sum of Numbers
{
public static void main(String[] args)
{
int sum = 0;
int count = 1;
int number = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
while (number >= count)
{
sum += count;
count ++;
}
System.out.println("Sum equals " + sum);
}
}
New to Java so anything will help!
You can take the input in a while loop, like so:
int number = 0; // start at 0 so the while loop is true for the first time
while (number < 1) {
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
}
This way it will keep asking them to input a number until the number they input is greater than 0.
Related
Im trying to get specfic outputs using these inputs:1 2 2 1 3 -1. The ouputs are suppose to be Count of positive integers is: 5
The highest value is: 3
The lowest value is: 1
The average is: 1.8
HOwever, im keep getting the wrong outputs for low and average value
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num, max, low, sum;
num= scnr.nextInt();
max = num;
low =0;
sum=0;
int count = 0;
double avg=0;
while(num>=0 )
{
num=scnr.nextInt();
if(num<max)
{
low = num;
}
else
{
max=num;
}
sum+= num;
count++;
}
avg=(double)sum/count;
System.out.println("Count of positive integers is: "+count);
System.out.println("The highest value is: "+max);
System.out.println("The lowest value is: "+low);
System.out.println("The average is: "+ avg);
}
}
For the suggested changes, I will stick to your code structure and you can further refine it:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num, max, low, sum;
num = scnr.nextInt();
max = num;
// Should not set low = 0, you should set low to the first read number also
low = num;
// You have already read one number above, sum should start from num
sum = num;
// You have already read one number above, count should start from 1
int count = 1;
double avg = 0;
while (num >= 0)
{
num = scnr.nextInt();
// You have to stop while loop if num < 0, you do not want to count negative number
if (num < 0)
break;
// If you have number smaller than low, set it
if (num < low)
low = num;
// If you have number bigger than max, set it
if (num > max)
max = num;
sum += num;
count++;
}
avg = (double)sum / (double)count;
System.out.println("Count of positive integers is: " + count);
System.out.println("The highest value is: " + max);
System.out.println("The lowest value is: " + low);
System.out.println("The average is: " + avg);
}
}
But note that there is a flaw for the above code if your input is only -1. I will leave this to you to have a try on how to fix that.
I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)
What is missing in my code in order to calculate the average of the inputted numbers from the user?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
float average;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
} while (n != 0);
if (n == 0) {
System.out.println("The average is : " + n);
}
scanner.close();
}
}
When the user puts in "0" then the programm should calculate the average of the inputted numbers by the user, that is why i wrote "while (n != 0)".
You should do something like this:
Note that as you have one more number (the zero), then you have to consider it when calculating the average by removing it, because you ask for 0 to finish the program.
public class Teste {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
double average = 0;
int qtdNums = 0;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
average = average + n;
qtdNums++;
} while (n != 0);
if (n == 0) {
System.out.println("The average is : " + average / (qtdNums - 1));
}
scanner.close();
}
}
You are not actually using the numbers that you are reading in. A good editor would tell you that before you even ran it. I would look into getting the Eclipse IDE. You will want to do something similar to that suggested by jhenrique. I would say it is probably better to add the numbers as integers and then cast later, so that you do not lose accuracy on floating point additions, which can cause you a lot of grief in some cases (but here you are probably fine). Here is my suggested code, modified from jhenrique's answer:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
int sum = 0;
int count = 0;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
sum += n;
count++;
} while (n != 0);
System.out.println("The average is : " + ((double) sum) / (count - 1));
scanner.close();
}
double is like float, but more accurate. In the loop, I add each read number to sum and then divide by the number of things read at the end to get the average.
Hi this is what a question on a course I am doing wants...
The program prints "Type numbers” until the user types the number
-1. When the user types the number -1, the program prints "Thank you and see you later!" and ends
the program should print the sum of the numbers entered by the user
(without the number -1).
the program should print how many numbers the user typed (without
the number -1).
the program should print the average of the numbers the user typed
(without the number -1).
5. the program should print the number of even and odd numbers that the
user typed (without the number -1).
I have completed 1-4 but am completely stuck on 5. I did make a start on trying to work it out including putting a for loop inside my while loop but apart from the fact it didnt work it looked well out of place so i removed it. Anyway here is what i have done so far which as I say all works in its own magical way.
And so if anyone can help me with question 5 that would be great. ps.I'm sure what i've done so far could have been written better but don't focus on that for now cos for me and where i am with Java this is nothing short of a miracle.x
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int sum = 1; // to counteract the -1 from the user
int total = 0;
double avg;
//int even = 0;
//int odd = 0;
System.out.println("Type numbers:");
while (true) {
int numbers = Integer.parseInt(reader.nextLine());
sum += numbers;
total++;
avg = ((double) sum) / (total - 1);
if (numbers == -1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + (total - 1));
System.out.println("Average: " + avg);
//System.out.println("Even numbers: " + even);
//System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You could store variables where one counts odd numbers and one counts even numbers. If the number is odd, increment the odd numbers variable. If even, increment the even numbers variable. Use the % operator to get the remainder of the input divided by 2.
int oddNumbers = 0;
int evenNumbers = 0;
if(numbers % 2 == 1){
oddNumbers++;
} else if(numbers % 2 == 0){
evenNumbers++;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner (System.in);
int sum = 0;
System.out.print("Enter limit number: ");
int limit = in.nextInt();
int oddNumbers = 0;
int evenNumbers = 0;
for(int i= 1;i<=limit;i++)
{
System.out.println("Enter limit number: "+i+"");
int numbers= in.nextInt();
if(numbers %2==0)
{
evenNumbers++;
}
else if(numbers %2==1)
{
oddNumbers++;
}
}
System.out.println("There are: "+oddNumbers+" odd numbers");
System.out.println("There are :"+evenNumbers+" even numbers");
}
}
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
int firstnum = 4;
int lastnum = 104;
int evncnt, oddcnt;
int count;
System.out.println("First number is " + firstnum);
System.out.println("Last number is " + lastnum);
count = lastnum - firstnum + 1;
System.out.println("Total numbers are " + count);
if (count % 2 == 0) {
System.out.println("Total even numbers are " + count / 2);
System.out.println("Total odd numbers are " + count / 2);
} else {
if (firstnum % 2 == 0) {
System.out.println("Total Even numbers are ");
System.out.println((count + 1) / 2);
System.out.println("Total Odd numbers are ");
System.out.println((count - 1) / 2);
} else {
System.out.println("Total even numbers are ");
System.out.println((count - 1) / 2);
System.out.println("Total odd numbers are ");
System.out.println((count + 1) / 2);
}
}
}
}
I am attempting a program that reads an unspecified number of integers, find sum, positive, negative and average. My issue is that either it will only run and allow one integer to be typed and then do nothing, or with the following code, it never stops letting you enter numbers therefore I can't get past. I have the number = 0 output correct.
public class Compute {
// Count positive and negative numbers and compute the average of numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
positive = 0;
negative = 0;
total = 0;
System.out.println("Enter an integer, the input ends if it is 0: ");
int numbers = input.nextInt();
do {
if (numbers > 0) {
positive++;//add 1 to positive count
} else if (numbers < 0) {
negative++;//add 1 to negative count
}//end else if
sum += numbers; //add integer input to sum
numbers = input.nextInt();
total++;
} while (numbers != 0);
if (numbers == 0) {
System.out.println("No numbers are entered except " + numbers);
}//end if
}
}
Try below code. to terminate the loop and see output type 0 as input at any time of execution.
import java.util.Scanner;
public class Compute {
// Count positive and negative numbers and compute the average of numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int positive = 0;
int negative = 0;
int total = 0;
System.out.println("Enter an integer, the input ends if it is 0: ");
int numbers = input.nextInt();
do {
if (numbers > 0) {
positive++;// add 1 to positive count
sum += numbers; // add integer input to sum
}
else if (numbers < 0) {
negative++;// add 1 to negative count
sum -= numbers; // add integer input to sum
}
numbers = input.nextInt();
total++;
} while (numbers != 0);
System.out.println("The number of positives is \t " + positive);
System.out.println("The number of negatives is \t " + negative);
System.out.println("The total count of number is \t " + total);
System.out.println("The sum of all number is \t" + sum);
System.out.println("The average is \t"
+ ((double) sum / (positive + negative)));
}// end main
}// end Compute
Following code snippet should give you a good example on how to read integers from console:
Scanner scanner = new Scanner(System.in);
do {
int i = scanner.nextInt();
// ...
} while (scanner.hasNext());
The scanner.hasNext() method call will block until user enter the next number on console