Printing smallest and largest number.Output is not what i wanted - java

Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers typed in by the user. You may assume the user enters a valid number greater than 0 for the number of numbers to read. Here is an example dialogue:
How many numbers do you want to enter? 4
Number 1: 5
Number 2: 11
Number 3: -2
Number 4: 3
Smallest = -2
Largest = 11
This is what i have done but i am unable to get the smallest and largest output.
import java.util.*;
public class smallestLargest{
public static void main(String[] args){
System.out.print("How many numbers do you want to enter? ");
Scanner sc=new Scanner(System.in);
int count=sc.nextInt();
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
for(int i=1;i<=count;i++){
System.out.println("Number" + i + ": ");
int nextNumber=sc.nextInt();
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
}
System.out.println("Smallest= "+ smallest);
System.out.println("Largest= "+ largest);
}
}

This is the problem:
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
That doesn't do what you want at all.
I'm not going to give you the solution, but think about it - just do one of them at a time. Let's start with "smallest".
If our current smallest number is 5, and someone enters 2, what should the new smallest number be? Why?
If our current smallest number is 5, and someone enters 10, what should the new smallest number be? Why?
Work that out, then apply the same thought process to "largest number".

Don't use "else if", because on the first loop, the number will pass both tests - i.e. it will be the smallest AND the largest, also don't use "+=", just "=" and change the "largest". So something like:
if(nextNumber<smallest)
smallest=nextNumber;
if(nextNumber>largest)
largest=nextNumber;

Little bit 'I am lazy' solution:
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt())
{
numbers.add(sc.nextInt());
}
System.out.println("Smallest= " + Collections.min(numbers));
System.out.println("Largest= " + Collections.max(numbers));

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.

Dynamic array in Java - so we can decide the size of an array according to user's input

I just wrote this basic program. It takes 5 values from the user and stores all of them in an array and tells the highest number.
import java.util.Scanner;
public class HighestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] numbers = new int [5];
int max = numbers[0];
System.out.println("Enter " + numbers.length + " numbers:");
for (int i=0; i<numbers.length; i++) {
numbers[i] = input.nextInt();
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is:" +max);
}
}
I'd like to take off the restriction of 5 numbers and allow the user to add as many numbers as he wants. How can I do that?
Appreciate the assistance. :)
Thanks
If the user knows the number of numbers in advance (before they enter the actual numbers):
Ask the user how many numbers they want to enter:
System.out.println("How many numbers?");
int numberOfNumbers = input.nextInt();
Use that as the array size:
int[] numbers = new int[numberOfNumbers];
If the user shouldn't need to know the number of numbers in advance (e.g. if they should be able to type "stop" after the last number) then you should consider using a List instead.
Alternatively, you could use an ArrayList and keep on adding elements until the user enters a blank line. Here is a tutorial on using ArrayList.
Some pseudocode could be:
numbers = new list
while true
line = readLine
if line == ""
then
break
else
numbers.add(convertToInteger(line))
...
The benefit of this approach is that the user does not need to even count how many numbers he/she wants to enter.

Squaring and totaling in java

So the challenge is to prompt the user to enter an integer value "count". Next
prompt them to enter "count" more values. Then square each value entered and add it to a main
value sum.Then display the sum of the square of all the numbers entered.
An example of the build output is like :
Please enter an integer value: 3
Please enter 3 numeric values:
7 8 3.5
The sum of the squares of each of these numbers is: 125.25
I'm still new to learning code, so I'm a bit lost at how to square multiple values on a single user input and also totaling them up. Can anyone offer some help?
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
sum_squares();
}
public static void sum_squares(){
Scanner in = new Scanner(System.in);
System.out.println ("Please enter an integer value:");
int count = in.nextInt();
System.out.println ("Please enter" + count + "more values:");
int square = in.nextInt();
}
}
You need to add a for-loop after:
System.out.println ("Please enter" + count + "more values:");
The for-loop should run for count times, and each time the loop is run, it should ask the user for an input. You can then take that input and square it (remember - squaring is as easy as multiplying a number by itself! 2 * 2 = 4, or 2-squared) Once you have the squared number, add it to a sum variable which you will have created before the for-loop. Then just print out the sum after the for-loop.
Here is a great tutorial on for-loops!

Can't figure why my program doesnt work

import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.
Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.
How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.
Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.
In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.
To fix this, don't progress your program until your input is valid using a while loop, like this:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}

In java, in this program it suddenly stops running properly at a certain point of code? but it compiles? any ideas what could be the issue?

import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.

Categories