java - Read & determine number of integers [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a new bee in java ... so I have an assignment and I am stuck can somebody help me
I have to write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zero's). The program should end when the user inputs 0.
Sample run:
Enter an int value (the program exits if the input is 0: 1 3 -1 2 0
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
The thing which i wrote is ... The logic seems right but it does not work ...
The code that I wrote is
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
while (data !=0)
{
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data < 0 || data > 0){
count++;
if (data >0)
positive++;
else if (0<data)
negative++;
count = count + data;
count++;
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of average is " + count/data ;
JOptionPane.showMessageDialog(null, strOutput);
}
}

In your while loop condition, you're checking if data !=0 which returns false and the while loop code block doesn't execute, because the data is set to int data = 0; at the beginning of program.
There are 2 simple solutions to your problem:
Set data to something other than 0
Use do...while loop, see example below
int data = 0;
...
do{
...
} while (data != 0);

Two errors here:
Your loop will never execute, since on the initial run, data == 0. You can fix this by asking the question early as opposed to later:
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
int data = Integer.parseInt(strdata);
Then, later in the loop (towards the bottom):
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
Even if you were able to enter the loop, you'd get all positive number counts and no negative number counts. The reason for this: data > 0 and 0 < data are equivalent boolean statements.
What you probably meant was this:
if (data > 0) {
positive++;
} else if (data < 0) {
negative++;
}

As others have said, initializing data to is a problem, but see below for my advice there.
The other issue you're going to run into is you're having count do too much.
Assume count starts at 0 and the user enters 3.
In
if (data < 0 || data > 0){
count++;
You're now at one, the you go into
count = count + data;
count++;
And count goes up to 4, then ++ up to 5.
Even if you've got a 0 entered, you still alter count before breaking the loop.
Try something like Orel mentioned with having a sum int that just keeps track of the sum. Keep count only to count, and only the count++ at the very bottom, completely erase
if (data < 0 || data > 0){
count++;
Instead, try something like this for the 0 check to prevent screwing with the whole thing:
while(true){
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data == 0)
break;
...
}
You could use a do/while here as well. This will allow you to initialize data to whatever (or nothing) that you like. Another thing, make sure that they value they enter is not null and is an int, your professor will definitely enter "sleirjwlfie" when prompted for a number because it's best practice to assume the user will break your program. So something in pseudo-code like:
while(true){
// get value from user
// if value is null OR value is not an int
continue;
}
I'll let you sort out the how to there as to not kill the learning experience, but I know that kind of thing bit me in school more than once.
Good luck!

+1 for attempting and writing almost working code :)
As others have pointed out your code has few bugs which needs to be fixed.
Your assignment to data should happen at least once before entering
while(data) loop.
You don't need to check value of input before incrementing count, if
it's 0 then you won't enter loop. Otherwise you will have to
increment count anyways.
For calculating total and average you need to use one more variable
Are you using any IDE ?
Use IDE (Eclipse is one of the best one) and debug your code step by step to check what's happening.
Google for how to use IDE and debug.
Below is working code for your reference.
import javax.swing.*;
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
int total = 0;
double avg = 0;
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
while (data !=0)
{
if (data >0) {
positive++;
} else {
negative++;
}
total = total + data;
count++;
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
avg = total * 1.0 /count ;
strOutput = "The number of average is " + avg;
JOptionPane.showMessageDialog(null, strOutput);
System.exit(0);
}
}

Well, the first problem is here. You initialize data to 0:
int data = 0;
Then your loop condition checks for data != 0 :
while (data !=0) {
...
}
Since data is assigned 0, the loop is never entered.

You should add a 'sum' int variable and change this line
count = count + data;
With this
sum += data;
Also change your while-loop to do-while loop.

Related

Issues with loops? Program runs as it should but test keep failing. Java using TMCbeans

I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.

Java: Adding and Subtracting Digits Taken from a String

So the purpose of this program is to get the user to enter an integer that the program will recognize as a string. Then the program has to be able to recognize each of the numbers entered and manipulate them as follows. Digits are to be added together if the digits are the same or if the next digit is greater. Digits are to be subtracted if the next digit is smaller.
An example:
The input "234224" should output 13(2+3+4-2+2+4)
However my program gives an output of 17.
I don't know how to fix the problem. My problem is in my first if statement. When the second occurrence of "2" is read I want the program to subtract 2 from the output being calculated but instead it adds 2 because of how I coded the first if statement.
Could someone give me a solution using the same method I used if possible?
public class StringManipulation {
public static void main(String[] args) {
String userInt;
int total = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
userInt = input.nextLine();
for (int k = 0; k < userInt.length(); k++) {
int presentNum = userInt.charAt(k);
System.out.println(userInt.charAt(k));
if (presentNum == userInt.charAt(0)) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
} else if (presentNum >= userInt.charAt(k - 1)) {
total += Character.getNumericValue(presentNum);
System.out.println("counter currently at (adding)" + total);
} else if (presentNum < userInt.charAt(k - 1)) {
total -= Character.getNumericValue(presentNum);
System.out.println("counter currently at (subtracting)" + total);
}
}
System.out.println("Output= " + total);
input.close();
}
}
Your problem is with your initial check
if (presentNum == userInt.charAt(0))
in other words, you do stuff if the number you're looking at is the same as the first number. In this particular case, that condition kicks in when you encounter the 2 later in the string, and you end up adding it instead of subtracting it.
You probably wanted that condition to be
if (k == 0)
if (presentNum == userInt.charAt(0)) {
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
System.out.println("counter currently at (same)" + total);
}
Your problem lies here. The first digit is added to the sum regardless of the previous digit. That means the output changes from 13(2+3+4-2+2+4) to 17(2+3+4 +2 +2+4).
You should have something like
if (k==0){
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
}
for the first digit.
Try to change the first if condition, as follows
if (k==0) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
}
Because, at the first iteration you have only one operand and you don't have take the value at 0th index for the condition, rather than that just see whether is it the first index.

Find two smallest value inputs

The instructions are: "Ask the user for the following information, in this order:
A terminating value (real number). The user will enter this value again later, to indicate that he or she is finished providing input.
A sequence of real numbers. Keep asking for numbers until the terminating value is entered.
Compute and output the smallest and second-smallest real number, in that order. It is possible for the smallest and second-smallest numbers to be the same (if the sequence contains duplicate numbers)."
I uploaded my code and the grading software gave me a zero saying the program is not consistent with the assignment, however, when testing my code it runs just as required for the assignment. Any feedback as to why this may happen would be appreciated.
This is my code:
public class TwoSmallest
{
public static void main (String[] args)
{
double terminator;
System.out.print ("Please enter a terminating value: ");
terminator = IO.readDouble();
double lowest1;
double lowest2;
System.out.println("Please enter sequence of numbers:");
lowest1 = IO.readDouble();
while (lowest1 == terminator)
{
IO.reportBadInput();
lowest1 = IO.readDouble();
}
lowest2 = IO.readDouble();
while (lowest2 == terminator)
{
IO.reportBadInput();
lowest2 = IO.readDouble();
}
double input;
do
{
input = IO.readDouble();
if (input < lowest1)
{
if(lowest2 < lowest1)
lowest2 = lowest1;
lowest1 = input;
}
else if (input < lowest2)
lowest2 = input;
}while (input != terminator);
System.out.println("RESULT: " + lowest1);
System.out.println("RESULT: " + lowest2);
}
}
Here are the two scenarios which are not handled by your solution :
For suppose you have given the sequence of numbers 3,7,1 the result of your code is 1 and 7 not 1 and 3.
It is because you are not changing lowest2 value when input < lowest1.
If your input is 3,1,7 where first number is lowest1, second number is lowest2 and then input variable value is 7 then the condition (input < lowest1) is false, so there will be no swapping of lowest1 and lowest2 values and the result will be 3 and 1 instead of 1 and 3.

What is causing my dice game to show an unrealistic amount of perfect rolls

I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.

Simple Java Query - Getting a Result from a Integer

I have been set an assignment where I must find the average of a list of positive numbers enterd by the user, the amount of numbers entered is unknown. So far I have got the program to add all numbers that have been entered (the entry teminates when a user enters 0). I do not want the answer to this question on here because I am really trying to learn this fast!
I am having trouble with the while statement,
I wanted to say
WHILE ( numberentered = 0 );
......
but this doesnt seem to work
I originally did it like so:
while ( numberentered >= 1 );
System.out.print (numbersum);
but this still jumps out of the do loop when a negative number is entered.
Any idea guys.... If you understand my question but it is still worded very badly... please edit.
Thank you.
while (numberentered != 0) { < read new number and add it to total and ... (but you didn't want the answer...) > }
Shouldn't you be doing this?
while(numberEntered != 0) {
// add it up
}
It seems like maybe you meant to do:
while (numberentered != 0) {
//do stuff
}
Note that no semicolon is needed on the 'while' line itself.
This is what I interpreted the problem statement:
"User is allowed to enter the numbers as many times but when it enters 0, the program would display the average of the numbers being entered prior to 0 and exit"
You may go this way:
public static void main(String args[]) {
float no = 0;
float average = 0;
int count = 1;
if(args.length == 0) {
printf("No number being entered...program exits");
System.exit(0);
}
if(args[0] == 0) {
displayAverage(average);
return;
}
for(count;count<args.length;count++){
try {
no = Float.parseFloat(args[count]);
if(no == 0 ) {
break;
}
average = average + no;
}
catch(NumberFormatException nfe) {
printf("Please enter only numbers");
}
}
average = average/count;
printAverage(average);
}
private void displayAverage(float average){
System.out.println("average is: "+ average);
}
hope this may helps..

Categories