Why does my code not run? - java

I have this code:
import java.util.Scanner;
public class PositiveNegative { public static void main(String[] args) {
int numbers, plus = 0, minus = 0;
int count = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while(numbers != 0)
{
total += numbers;
if(numbers > 0)
plus++;
if(numbers < 0)
minus++;
}
System.out.println("The number of positives is: " +plus);
System.out.println("The number of negatives is: " +minus);
System.out.println("The number of total is: " +total);
}
}
The problem with is that I try to run it and type the numbers but it does nothing. I want it so that when you type 0 it stops taking numbers and starts processing the code. What should I do?

Try this:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int numbers = 0, plus = 0, minus = 0;
double total = 0;
do{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = Integer.valueOf(scan.nextLine());
total += numbers;
if (numbers > 0)
plus++;
if (numbers < 0)
minus++;
}
while (numbers != 0);
System.out.println("The number of positives is: " + plus);
System.out.println("The number of negatives is: " + minus);
System.out.println("The number of total is: " + total);
}
}
Put your Scanner in the while loop so that everytime loop start it will ask for User input.

You need to update numbers or your loop will run for ever. And I recommend using braces (and an else). Something like,
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
}
Alternatively, you could use a do-while loop. Then you only need one copy of the prompt. Like,
do {
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
} while (numbers != 0);

You have to modify numbers each time to make it work in your while.
So, in your existing code, just comment out numbers = scan.nextInt(); and use below--
// numbers = scan.nextInt(); //comment out this call
while ((numbers = scan.nextInt()) != 0) {
....
this will give you desired output--
Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0

Related

How to make while loop check if there are 16 digits in a string

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}

Java loop until user enters a value of 0. The values must be between 1-4 and if over 4, ask user to try inputting again

I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average. Typing 0 will end the program and calculate the average. Any value greater than 4 or less than 0 should not count and ask the user to input the value again. I'm stuck on the last part. I'm not sure if the while loop is the correct loop to use either. Thanks for any help
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0)
break;
if (num > 4)
System.out.println("Invalid number");
sum += num;
count += 1;
}
System.out.println("Average: " + sum/count);
}
You will always hit the lines:
sum += num;
count += 1;
Because the code just drops through from the second if statement.
The following would work - note the else if and else blocks will only be executed when the first if drops through:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0) {
break;
}
else if (num > 4) {
System.out.println("Invalid number");
}
else {
sum += num;
count += 1;
}
}
System.out.println("Average: " + sum/count);
}

Read a list of nonnegative integers and to display the largest integer, the smallest integer and the average of all the integers

I have encountered some problems with the calculating of largest and smallest number... If the first number I entered is a larger number than the 2nd number input, it will not record the 1st number into the largest...
Take a look at the output, it will help elaborate better..
Calculation Error.. &
1st input problem..
Codes below!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
You could build an IntStream if you are using Java 8, and extract those numbers automatically using IntSummaryStatistics. You can find the official documentation from Oracle here.
Here is the code to achieve that:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
If you input 8 3 7 the output will be:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
I hope it helps!
Do it like this:
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
}
//REMOVED ELSE ADDED another IF
if (number > largest){
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
The problem is your if statement, as the logic is flawed. If the input number is smaller than smallest, then you update the smallest number. So far all is correct. The problem occurs, because you update largest in the else part. This means, if a number is not the smallest, largest is overwritten. But if the number is greater than the smallest, it is not automatically the largest. The right way to do this, is to check if the number is larger than the largest in a new if statement and update largest only in this case.

How do I display even and odd numbers based on user input? - java

Please help... I need to write a program that displays even and odd numbers based on user input, but it loops forever during my last print statement.
Here is what I have so far, what's wrong?
import java.util.Scanner;
public class Integer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
while(n >= 0) {
System.out.println("Now enter " + n + " integers: ");
int num = input.nextInt();
while(num > 0) {
for(int i = 0; i <= n; i++){
if (i % 2 == 0) {
even++;
}
else {
odd++;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
}
}
}
}
}
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
while (n > 0) {
System.out.println("Now enter integer " + n + ": ");
int num = input.nextInt();
if (num % 2 == 0) {
even++;
} else {
odd++;
}
n--;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
Explanation:
You handle n inputs from user and just check if the input is odd or even with an if-statement. You were over-complicating it.
You have a couple of issues with too many while loops. You don't decrement n anywhere but you also loop on num while it's greater than 0. So it will loop forever if they stick something other than 0 in there.
System.out.println("Now enter " + n + " integers: ");
while(n >= 0) {
int num = input.nextInt();
if(num > 0) {
if (num % 2 == 0)
even++;
else
odd++;
}
n--;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
The infinite/forever loops is happening because of input.nextInt() and this is due to the behavior of next() method of Scanner class.
next(), nextInt() and its other variations do not move the cursor to the next line (end of current line - instead reads the first complete token with default delimiter as whitespace). nextLine() method on the other hand reads the whole input and moves the cursor to the next line.
Your code can be fixed by adding input.nextLine() to move the cursor to the beginning of the line before taking the next input. See below modified code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
for(int i = 0 ; i < n; i++) {
System.out.println("Now enter integer " + (i+1) + " of " + n + " integers: ");
int num = input.nextInt();
while(num < 0) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//this line is needed to move the input cursor to next line (due to use of nextInt() above)
input.nextLine();
if(i%2==0) {
even++;
} else {
odd++;
}
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
}

while loop - sum of even numbers and its average

http://pastebin.com/w8KntkE6#
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0) {
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
} else if (num % 2 != 0) {
continue;
}
System.out.println();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
}
}
}
The code executes and it sums even numbers. However, when a odd number enters it returns an error or it breaks. I want it ignore any odd number. What is wrong with my code?
You continue the loop on odd numbers without modifying num - looks like it should infinite loop to me.
Am I missing something, or are you missing a nextInt() when you have an odd number? Since in the if even you have num = scan.nextInt();. You don't when num is odd.
Change
else if (num % 2 != 0){
continue;
}
to
else if (num % 2 !=0){
num = scan.nextInt();
continue;
}
just before continue statement add following code. I hope it will work correctly.
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
Change to:
package javaapplication9;
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication9 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
while (num >= 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0)
{
count++;
sum += num;
System.out.println("The sum so far is " + sum);
System.out.print("Enter an integer (0 to quit): ");
num = scan.nextInt();
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
num = scan.nextInt();
}
}
Try this. I'm not quite sure when do you want to print the average, you could move it out of the while loop if you want to print it at the end.
public static void main(String[] args) {
// TODO code application logic here
{
int sum = 0, num, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
while ((num = scan.nextInt())> 0) // sentinel num of 0 to terminate loop
{
if (num % 2 == 0){
count++;
sum += num;
System.out.println("The sum so far is " + sum);
if (count == 0) {
System.out.println("No nums were entered.");
} else {
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is " + fmt.format(average));
}
}
System.out.print("Enter an integer (0 to quit): ");
}
System.out.println("end");
}
}

Categories