When we enter 0 in the program it is supposed to stop running the loop and print the average of the numbers. When I run the program and initially enter 0, the program exits. If I enter in an integer that is not zero first, and then enter 0, the program keeps running and I can't quit.I figure that the integer value needs to update when the user enters a new value for the program to quit, and the sum to be correct.
How do I update the integer value while the loop is running? I should change or add something in the loop I'm guessing.
import java.util.Scanner;
public class Exercise05_01 {
public static void main(String[] args){
float negCount = 0;
float sum = 0;
float posCount = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a positive or negative integer. Entering 0 ends program");
int integer = input.nextInt();
while (integer != 0) {
if (integer > 0) {
posCount = +1;
sum = +integer;
}
if (integer < 0) {
negCount = +1;
sum = +integer;
}
float count = negCount + posCount;
if (integer == 0) {
System.out.println("The answer");
}
}
}
}
There are two problems.
First, you don't get any input while you're in the loop. That's fixable with a suggestion provided earlier by Lunchbox.
Second, this is not accumulating the value:
posCount = +1;
That assigns a positive 1 to posCount every time.
You want to either increment the value...
posCount++;
...or add one explicitly.
posCount += 1;
I think you need to add the line that gets input in your while loop.
while (integer != 0) {
integer = input.nextInt();
.
.
.
This way while the loop is running, every iteration it will check for an input still.
Also I have to say this looks suspiciously like homework... especially the class name...
As Lunchbox points out in his answer, you need to request input from the user from inside your loop, otherwise integer never changes and you never exit your loop; the behaviour you're observing is the program running forever.
The best way to do this is Lunchbox's suggestion:
int integer = input.nextInt();
while(integer != 0){
// Do stuff
integer = input.nextInt();
}
However, you have many other problems with your code. For one thing, why are you using floats to store your counters and sum values? Why not use ints?
For another, you're never actually incrementing those values. As Makoto points out in his answer, the line posCount = +1 is not an increment operator.
In that case, the + operator is the unary plus operator. What this will do is force your signed value to be positive, so +(-1) == 1. While this is useful, it's not what you want to happen, and it's definitely not what you want to be doing around your sum.
Instead, you want to do one of the following three things:
posCount = posCount + 1;
posCount += 1;
posCount++;
Those are all equivalent statements. The ++ operator is the postfix increment operator, which will add 1 to the value of the variable and then return it (It's slightly more complicated than that, but you can read that on your own time). So don't use that syntax for your sum; use one of the other two.
Related
The program listed is about writing the Fibonacci series given user input that is below 100. The problem that I am having is figuring out how to get the Fibonacci to not print if the number listed by the user is above 100. However, I am unable to figure out what to do. This is my code, I am not trying to use while loop to only print if the number is between 1 and 100. however when I print 101, it still gives me the Fibonacci series.
import java.util.Scanner;
class Program_2 {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer between 1-99: ");
int num = console.nextInt();
while (num>1) {
if(num<100) {
System.out.println("Fibonacci Series till " + num + " terms:");
}
int n = 100, firstTerm = 0, secondTerm = 1;
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + ", ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
}
The Output that im getting when i print 101, is
I've used an if/else statement, but for some reason, it didnt do anything. Then I tried using a while loop and an if statement, but its still printing above 100. I am unsure how to go about this. Any help is very much appreciated!
To fix this issue, you can add another condition into your while loop. Right now, you are going into the while loop as long as num is greater than 1. Thus, numbers above 100 are being considered as well. To fix this, you can make your while loop start like this: while(num>1 && num<=100).
Your while check "while(n>1)" will run infinitely. You need to change num's value after every iteration like this:
num--; //In the loop
And when num becomes less than 1, the program exits from the loop.
If you want to check whether num is less than 100 or bigger than 1 use if statement(to check if input value corresponds to your range)
while(num > 1 && num < 100){
//your code in while loop
}else{
System.out.println("Your value is too big or too small!");
}
And also I've noticed your output of fibonacci sequence is not right(negative values, bound in int32). You can't even display in long values because fibonacci of 9*th order are over quadrillions. Try to use BigInteger in order to show right values in the console output. Want to fancy your output? Use /t and %n in System.out.print();
I'm doing a small program, and I ran into a problem.
Thing is I want to confirm that (in this case loop goes through 2 times) that the entered data was the same both times. If it's wrong it should output at the end that it's not correct.
int yearInput;
int monthInput;
int i = 2;
int x = 1;
int inputvalid;
int same = 0;
while (x == 1) {
while (i >= 1) {
System.out.println(i);
i--;
System.out.println("enter year");
yearInput = kb.nextInt();
System.out.println("enter month");
monthInput = kb.nextInt();
}
x--;
}
same = ???;
if(same==0){
System.out.print("Both loop inputs are same");
}
else{
System.out.println("Both loop inputs are not same");
}
}
While this program is just to show the problem, x and i values are variables in the real program, I just can't go through this segment.
You are first using two arrays which result in a nested loop which is probly something you don't want. If you wanted to check the results of two loops you'd create one loop with user inputs then store it in variable called something like loopOneResult. In the second loop you could do the same, then outside of both loops compare the results using the method equals or equalsIgnoreCase. This will surely tell you if the loops are the same. If this helps approve this answer :)
My Question that I am trying to solve is as follows: "Read in numbers from the user until the user enters -1, and compute the frequency of even numbers from the user".
I have the first part done and it seems to run ok. But I cant get the second part completed where I compute the frequency of even number from the user.
I have copied what I have done so far but i am looking for help to finish it of. I would appreciate anyone's help.
import javax.swing.JOptionPane;
public class Ex2Ass2ParC {
public static void main(String[] args){
String dataString = JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
int data = Integer.parseInt(dataString);
int count = 0;
while(data!=-1){
count++;
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
}
JOptionPane.showMessageDialog(null, "The frequency of numbers is"+count);
}
}
}
Add an if statement to check if a number is even instead of just adding to count every time by doing:
if (data % 2 == 0) {
count++;
}
So replace count++ with the statement above.
EDIT
If by frequency you mean percentage, you'll need to create a second local variable that keeps track of the total amount of numbers given
double totalNumbers = 0.0;
while(data!=-1){
totalNumbers++;
if (data % 2 == 0) {
count++;
}
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
}
And then change the dialog to JOptionPane.showMessageDialog(null, "The frequency is: " + (count/totalNumbers));
In order to compute frequency of numbers of a certain kind you need to count how many such numbers were entered, in addition to the total count of numbers, which you already have.
Add a separate counter, and increment it each time that data % 2 == 0, which indicates that the parsed number is even:
int count = 0;
int even = 0;
while(data!=-1){
count++;
dataString = javax.swing.JOptionPane.showInputDialog("Enter an integer value:/n(the program exits if the input is -1)");
data=Integer.parseInt(dataString);
if (data % 2 == 0) {
even++;
}
}
At the end of the loop divide the count of even numbers by the total count. Make sure that you cast the first count to double before performing division, otherwise you would get an integer division resulting in zero or one.
Alright, so my goal is to complete the following assignment:
"Design and implement an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard.
SPECIFICATION OF PROMPTS, LABELS AND OUTPUT : Your code should not have any prompt at all. The input to this program is a single integer . After the integer is read, the output consists of three lines. The first line consists of the number of odd digits in the integer followed by the label "odd digits". The second line consists of the number of even digits in the integer followed by the label "even digits". The third line consists of the number of zero digits in the integer followed by the label "zero digits". For example, if 173048 were read in, the output would be:
3 odd digits
3 even digits
1 zero digits
SPECIFICATION OF NAMES: Your application class should be called DigitAnalyst"
And the code I have produced is:
import java.util.Scanner;
public class DigitAnalyst{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String num = scan.next();
int odd_count = 0;
int even_count = 0;
int zero_count = 0;
//input an int as a string, and set counter variables
int[] num_array = new int[num.length()];
//ready a array so we can so we can parse it sanely
for (int i =0; i < num.length(); i++)
{
num_array[i] = num.charAt(i);
}//fill the array with the values in the initial number using a loop
for ( int i=0;i< num_array.length; i++)
{
if (num_array[i] % 2 ==0)
{
if (num_array[i] ==0 )//the hell is going on here?
{
zero_count++;
}
else if (num_array[i] != 0)
{
even_count++;
}
}
else if (num_array[i] % 2 != 0)
{
odd_count++;
}
}//use this loop to check each part of the array
System.out.println(odd_count+ " odd digits");
System.out.println(even_count+" even digits");
System.out.println(zero_count+" zero digits");
}
}
And yet I keep getting the wrong output. More specifically, it returns the correct amount of odd numbers but it keeps counting 0 as an even and not as a zero.
I know where the problem is but I have no idea what is wrong, and I've spent a few hours on this.
If someone could point me in the right direction I'd be ectstatic.
When you encounter a problem that involves the manipulation of digits in an integer, the standard approach is to use an actual integer and the operator %, rather than strings. Instead of scan.next() use
int num = scan.nextInt();
And then you can do this:
do {
int digit = num % 10;
if ( digit == 0 ) {
zero_count ++;
} else if ( digit % 2 == 0 ) {
even_count ++;
} else {
odd_count ++;
}
num /= 10;
} while ( num > 0 );
The idea is that when you divide a number by 10, the remainder is exactly the rightmost digit, and the quotient will have all the other digits. That's simply how the decimal system works.
In this method you get the digit directly without calling any method, and you don't need any arrays.
If you assign the integer element with num.charAt(i) the ASCII value of the character is assigned and you get wrong results. In order to fix this, change
num_array[i] = num.charAt(i);
to
num_array[i] = Integer.parseInt(String.valueOf(num.charAt(i)));
or similar.
I'll give you some help here. First, charAt() returns the character at the index in the string, as a char data type. You're storing in an array of ints, which is assuming the numerical value of the character in the set, not the actual value.
Try this instead...
Change:
int[] num_array = new int[num.length()];
to:
char[] num_array = new char[num.length()];
and wrap all your num_array[i] references in your conditionals with:
Character.getNumericValue(num_array[i])
You should get your expected results.
Input = 12340
Output =
2 odd digits
2 even digits
1 zero digits
Below is one of the first programs I made (with help from the Internet) in Java. It is a program that checks if a given integer is prime or not and prompts the user with feedback. If the user input is not an integer it outputs that it is not an integer. The latter also happens when Big Integers are entered. This is the code:
import java.util.Scanner;
class BasicPrime1 {
public static void main(String[] args) {
try {
System.out.println("Enter an Integer: ");
Scanner sc = new Scanner(System.in);
int i;
int number = Integer.parseInt(sc.nextLine());
// 1 and numbers smaller than 1 are not prime
for (i = 1; number <= i;) {
System.out.println("NOT a prime!");
break;
}
// Number is not prime if the remainder of a division (modulus) is 0
for (i = 2; i < number; i++) {
int n = number % i;
if (n == 0) {
System.out.println("NOT a prime!");
break;
}
}
// I do not understand why the if-statement below works.
if(i == number) {
System.out.println("YES! PRIME!");
}
}
catch(NumberFormatException nfe) {
System.out.println("Not an integer!");
}
}
}
This program does his job, but I do not know why the part with the if-statement works. How is it possible that "i == number" gives a value of true (it prints out "YES! PRIME" when you enter a prime)? The local variable i gets incremented in the for-loop, but the if-statement is outside of the for-loop.
/edit the paragraph below is nonsense as Jim Lewis points out
Thinking about it now, the only reason I can think of that this is the case is because the == operator checks if the i-'object' and number-'object' belong to the same 'type' (i.e., have a reference to the same object). Since they both belong to the type of primitive integers this program catches the integers (other input throws a NumberFormatException which is caught and outputs "Not an integer"). The ones that are primes pass the first for-loop and then the magical if-statement gives "true" and it prints out "YES! PRIME!".
Am I on the right track?
I have improved this program by removing the magical if-statement and changing it for an if-else-statement like this: (/edit fixed problem with code thanks to answer of ajb)
boolean factorFound = false;
for (i = 2; i < Math.sqrt(number) + 1; i++) {
int n = number % i;
if (n == 0) {
factorFound = false;
break;
}
else {
factorFound = true;
}
}
if(factorFound == false) System.out.println("NOT a prime!");
if(factorFound == true) System.out.println("YES! PRIME!");
By only going up to the square root of the input number the calculation time improves (I know it can be even more improved by only checking odd numbers or using a AKS Primality Test, but that is beside the point).
My main question is why I could not improve the efficiency of the first program (with the magical if-statement) in the same manner. When I enhance the for-loop like this "(i = 2; i < Math.sqrt(number) + 1; i++)" in the first program it does no longer print out "YES! PRIME!" when you input a prime. It gives a blank. Even if my previous explanation is correct - which it is probably not - this is not explained.
You may enlighten me.
ANSWER: int i is outside of scope of for-loop and after going through the for-loop multiple times upto number the value of i will reach the value number, when we can be sure it is a prime. Furthermore, after checking the disappearing "YES! PRIME!" statement once again it turns out it is actually possible to change number in both the if-statement and for-loop to ( Math.sqrt(number) + 1 ) and have working code. So the question was based on a false premise.
i is declared outside the for loops, so its value is still in scope and available after the loop
finishes (nothing to do with comparing data types or anything like that!).
If no divisors were found, the i < number loop condition will eventually
fail, with i == number. (If the loop finds a divisor and hits the break statement,
that condition no longer holds).
When you do the sqrt optimization, the end condition of the loop is changed,
so i == number no longer holds after the loop exits, even if the number is prime.
In my opinion it would be more clear to explicitly set a flag (e.g. isPrime=0 just
before breaking out of the loop), then check that flag rather than looking at the
loop variable to see whether the loop completed or not.
// I do not understand why the if-statement below works
Explanation: Because i has been incremented until it equals number. If you stop at sqrt(number) then the if statement will always fail.
By the way I don't like using square root with integers. I like this better for a isPrime function:
if (number < 2) return false;
if (number > 2 && number % 2 == 0) return false;
for (int i = 3; i * i <= number; i = i + 2)
if (number % i == 0) return false;
return true;