I'm Stuck with my homework. Basically,we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0. However we are not allowed to user arrays for this problem.
and one more condition : If the largest value appears more than once, that value should be listed as both the largest and second-largest value, as shown in the following sample run.
I have met the first condition of the program however I cannot meet the 2nd condition.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I have tried to use this code.
if(num >= max2nd && num <= max1st) {
max2nd = num;
}
however when I run the program
https://imgur.com/a/YMxj9qm - this shows.
It should print 75 and 45 . What can I do to meet the first condition and meet the second condition?
If you exceed your maximum number (max1st), your new maximum number will be set to num. But your second largest number will be the current maximum number. So try this condition:
if (num > max1st) {
max2nd = max1st;
max1st = num;
} else if (num > max2nd) {
max2nd = num;
}
Please user If else in those cases. You have used two if statements that is replacing the value of max2nd.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
else if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I changed the conditions, please take a look
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
num = sc.nextInt();
while(num != 0) {
System.out.print("Integer No." + count + " ");
if(num > max1st) {
if(max1st > max2nd) {
max2nd = max1st;
}
max1st = num;
} else {
if(num > max2nd) {
max2nd = num;
}
}
count++;
num = sc.nextInt();
}
System.out.println("");
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
Here is a much simpler method.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
do
{
num = sc.nextInt();
max2nd = (num >= max1st) ? max1st : (num > max2nd) ? num : max2nd;
max1st = num > max1st ? num : max1st;
}
while(num != 0)
System.out.println("\nThe largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
If you need any more explanation I will be happy to help.
You can try below approach, this should solve your issue =>
import java.util.*;
public class BackedList {
private static Scanner sc;
public static void main(String args[]){
sc = new Scanner(System.in);
int num = 1;
List<Integer> integersList = new ArrayList<Integer>();
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
integersList.add(num);
}
Collections.sort(integersList, Collections.reverseOrder());
if(integersList.get(0) == integersList.get(1)){
System.out.println("The number " + integersList.get(0) + " is first largest and "
+ integersList.get(1) + " is the second largest number");
}
else
{
System.out.println("The largest number is :" + integersList.get(0) + " and the smallest one is :"
+ integersList.get(integersList.size()-1));
}
}
}
You can use the collection to get the largest and second largest like :
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
list.add(2);
Collections.sort(list);
int firstLargest = list.get(list.size()-1);
int secLargest = list.get(list.size()-2);
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num > max1st) {
max2nd=max1st;
max1st = num;
}
else if(num == max1st ) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
you are over complicating things with && in your if. if a number is greater than 1st 1sr gets changed if a number is same as first 2nd gets changed if its not bigger or same nothing happens.
Related
I have a program that prompts a user for integers until they type a value to continue the program onto the next step. How would I increment a variable called count every time the user inputs an integer? I'm using count++ to increment the count amount by the way, I just don't know how to make it go up when the user puts in data.
Code so far
//variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
//loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
high = num;
low = num;
//higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
It's simple. Just put count++ inside the while loop as follows,
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
// loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++; // here it goes
high = num;
low = num;
// higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You can put count++; anywhere in your do loop.
I understand why you're using it but why use the counter at all?
The code below uses a different technique to acquire integers from the User. It also ensures that the supplied number is indeed a integer that falls within the Integer.MIN_VALUE and Integer.MAX_VALUE range:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
System.out.print("Enter an integer, (q to quit): --> ");
input = userInput.nextLine().toLowerCase();
if (input.equals("q")) {
if (low == Integer.MAX_VALUE) {
low = 0;
}
break;
}
if (!input.matches("^-?\\d+$")) {
System.err.println("Invalid Entry (" + input + ")! "
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
boolean invalidInteger = false;
long tmpVal=0;
try {
tmpVal = Long.parseLong(input);
} catch(NumberFormatException ex) {
invalidInteger = true;
}
if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
System.err.println("Invalid Entry (" + input + ")! " + ls
+ "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
+ " Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
num = Integer.parseInt(input);
if (num > high) {
high = num;
}
if (num < low) {
low = num;
}
input = "";
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
If you want to keep track of how many entries the User made then you can still apply a counter if you like.
Im trying to make this program work but im getting the error that it cant find the variable min and max in the system.out.print statement in main method. I guess it is because main doesnt know what those variables are since the MinMax destroys those variables once its ran. But how can I transfer the results over from my MinMax method so that results will be printed in system.out.print in main method statement?
class MethodMinMaxWithUnlimitedValues {
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
Make them static and global
import java.util.Scanner;
class MethodMinMaxWithUnlimitedValues {
static int min = Integer.MIN_VALUE;
static int max = Integer.MAX_VALUE;
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
NOTE: that can have side effects
I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number (0 to quit): ");
//largest to-do
double largest = scan.nextDouble();
double count = 0;
while (largest != 0) {
double input = scan.nextDouble();
//max
if (input > largest) {
// not zero
// while (input > largest){
//
// }
largest = input;
//counter
count = 0;
}
//counter start
if(input==largest){
count++;
}
if (input == 0) {
System.out.println("Largest #: " + largest);
System.out.println("Occurance: " + count);
}
}
}
}
This program works! however, its not that complete I think...
Like if a user tries to enter
-17 -5 -2 -1 -1 -1 0
it outputs:
Max: 0
Occurrence: 1
Though: in my mind I want it to be:
Max: -1
Occurrence: 3
how would I do this WITHOUT using arrays? I know its in that part of the code I started above the counter.
Thanks in advance.
Why not something like that?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number (0 to quit): ");
double largest = 0, nextDouble;
int count = 0;
while ((nextDouble = scan.nextDouble()) != 0) {
if (nextDouble > largest || largest == 0) {
largest = nextDouble;
count = 1;
}
else if (nextDouble == largest) count++;
}
scan.close();
if (count == 0) {
System.out.println("No number entered!");
return;
}
System.out.println("Largest #: " + largest);
System.out.println("Occurance: " + count);
}
}
I am currently struggling with one thing about this assignment. I would just like a way to make the whole code shorter, even just a little bit (especially the if statement).
package Integers;
import java.util.Scanner;
public class SumOfInt {
public static void main(String[] args) {
int positive = 0;
System.out.println ("-Input ten non-zero integers to calculate their sum. " + "\n" + "-Input the integers at the console and press <Enter>" + "\n");
System.out.println ("Input the 1st integer:");
Scanner input = new Scanner (System.in);
int num1 = input.nextInt ();
System.out.println ("Input the 2nd integer:");
int num2 = input.nextInt ();
System.out.println ("Input the 3rd integer:");
int num3 = input.nextInt ();
System.out.println ("Input the 4th integer:");
int num4 = input.nextInt ();
System.out.println ("Input the 5th integer:");
int num5 = input.nextInt ();
{ if (num1 > 0)
positive++;
}
{ if (num2 > 0)
positive++;
}
{ if (num3 > 0)
positive++;
}
{ if (num4 > 0)
positive++;
}
{ if (num5 > 0)
positive++;
}
System.out.println ("The number of positive integers are: " + positive);
}
}
If you find yourself writing very similar code over and over again (or even copy-pasting stuff), there is always a way to generalise the code and put in into a for loop or an extra method. And that is the way to go.
In your case you could just simply use a for loop.
public static void main(String[] args) {
int positive = 0;
System.out.println("Input the integers at the console and press <Enter>");
Scanner input = new Scanner (System.in);
for (int i = 1; i <= 5; i++) {
System.out.println("Input the " + i + "st integer:");
int x = input.nextInt();
if (x > 0) positive++;
}
input.close();
System.out.println ("The number of positive integers are: " + positive );
}
Try this
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++) {
String place = i + "th";
if (i == 1)
place = "1st";
if (i == 2)
place = "2nd";
if (i == 3)
place = "3rd";
System.out.println("Input the " + place + " integer:");
if (input.nextInt() > 0)
positive++;
}
input.close();
System.out.println("The number of positive integers are: " + positive);
If you want to store the variable for later use, you can Use array to make it easier.
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int positive = 0;
for (int i = 0; i < 5; i++) {
array[i]=input.nextInt();
if (array[i] > 0)
positive++;
}
System.out.println("Number of positive elements are"+ positive);