Find two smallest value inputs - java

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.

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 - while loop for scanner validation results in failed input

I am trying to add the following scanner validation as follows;
public void promptFilmRating() {
while (!filmScanner.hasNextInt()) {
System.out.println("Please enter a number instead of text.");
filmScanner.next();
}
while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
filmRatingOutOfFive = filmScanner.nextInt();
}
}
However when using the code that relates to the integer between value validation, repeated inputs are needed in order to record the original input and I am unsure on how to correct this, any advice would be fantastic.
I believe your problem is in while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {.
Every call to filmScanner.nextInt() asks the stream for a new integer, so by calling .nextInt() twice in the while statement, you are asking for two numbers.
You might want to consider combining your two loops into one.
Example:
int myNum;
do {
myNumb = filmScanner.nextInt();
} while (myNum > 5 || myNum < 1);
Store the value that you are getting in a variable, and use that variable to perform the checks.
Here is an example:
private void promptFilmRating() {
Scanner filmScanner = new Scanner(System.in);
int filmRatingOutOfFive;
do{
System.out.println("Please enter your rating for the film:");
filmRatingOutOfFive = filmScanner.nextInt();
if(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1)
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
}while(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1);
System.out.println("You rated this film: "+filmRatingOutOfFive+" out of 5");
}

How do I read different inputs from scanner in Java?

I need to get various integral inputs and then when -1 is entered, the program should show the largest, smallest, sum of all entered, number of values of all entered, and the mean of all values entered. I have started a loop to take various inputs but cannot find a suitable way to read them and then play with them. I have searched everywhere on the internet.
import java.util.Scanner;
public class Exercise16 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a Positive integer or -1 to quit.");
while (!s.nextLine().equals("-1")) {
System.out.println("Please enter a Positive integer or -1 to quit.");
}
}
}
s.nextLine() reads your input
You should save it to a variable.
Also using a do-while to prevent the copied print statement
Scanner s = new Scanner(System.in);
String in; // where to save next input value
do {
System.out.println("Please enter a Positive integer or -1 to quit.");
in = s.nextLine();
// TODO: parseInt, check for positive number
} while (!in.equals("-1"));
If you want to track mins and maxes, you need two additional integer values.
If you want to track averages, you need a list.
Best of luck
You first need to read integer from command line. For that you have to use
s.nextInt();
Once you get this you have to get largest and smallest number, you can get these using 2 variables.
For average you can store sum and number of times user asked for input, 2 more variable. No need to store elements in list or some other storage.
If you want to see numbers entered than you have to store else you don't have to.
For storing use :
List<Integer> numbers = new ArrayList<Integer>();
For adding number you can use add method of List.
public static void main2() {
Integer laregst = Integer.MIN_VALUE;
Integer smallest = Integer.MAX_VALUE;
Integer sum = 0;
Integer count =0 ;
Scanner s = new Scanner(System.in);
int temp = s.nextInt();
while (temp != -1) {
if(temp > laregst){
laregst = temp;
}
if(temp < smallest){
smallest = temp;
}
sum += temp;
count += 1;
System.out.println("Please enter a Positive integer or -1 to quit.");
temp = s.nextInt();
}
System.out.println("Largest : "+(count == 0?"NA":laregst)+" Smallest : "+(count == 0?"NA":smallest)+" Mean : "+(count == 0 ? "NA" : ((sum *1.0/count))));
}
if you wont to read Multible Integers Value in Same Line you Can use s.nextInt() to read one Integer Value in each time

Reversing digits in Java. Leading and trailing zeros won't print

The problem was to reverse user entered digits. I have it working but while testing it I realized that it won't print either leading or trailing zeros.
For example if I enter 10 it only displays 1 in the result.
If I enter 0110 I get a result of 11.
Here is my code:
public class ReversingDigits {
int value;
int reverse;
public ReversingDigits() {
value = 10;
reverse = 0;
}// end constructor
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
value = input.nextInt();
if (value < 10 || value > 9999){
System.out.print("Please enter a valid 2-4 digit number: ");
value = input.nextInt();
}
while (value > 0) {
reverse *= 10;
reverse += value % 10;
value /= 10;
}
System.out.println("Reversed numbers are: " + reverse);
}
}//end class
Any ideas on how to get the zeros to print?
Thanks
Make sure you work with a String while reversing your number. It will preserve leading zeros. As you know 00001 is the same as 1 when in int representation, and so converting that to a string will remove all leading zeros.
Here's your code sample modified to read a string from the input, and only convert it to an int when you need to check the range.
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
String value = input.next();
int valueInt = Integer.parseInt(value);
if (valueInt < 10 || valueInt > 9999){
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
}
String valueReversed = new StringBuilder(value).reverse().toString();
System.out.println("Reversed numbers are: " + valueReversed);
}
Note that in your code, if a user enters the wrong range twice in a row, your program won't prompt him again. You may want to put this part of the code into a do-while loop which only exits when the input range is correct. Example
do {
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
int valueInt = Integer.parseInt(value);
} while (valueInt < 10 || valueInt > 9999);
//only get here when inputted value finally within target range.
Edit: As mentioned by #Levenal, you may also want to wrap Integer.parseInt in a try/catch block for NumberFormatException in the event the user passes in a non-numerical input.
As has been pointed out, reversing numbers you are much better off reversing a string. If you are allowed to stray away from console input, JOptionPane is quite good for simple String input, like so:
while(true){
String input = JOptionPane.showInputDialog("Please anter a number between 10 & 9999: ");
if(input == null){//If input cancelled
break; //Exit loop
} else if(input.matches("\\d{2,4}")){//Regex for at least 2 but no more than 4 numbers
System.out.println(new StringBuilder(input).reverse().toString());//Reverse
break;
}
}
Good luck!

Terminating loops with strings. (Java)

Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}

Categories