This question already has answers here:
How do I determine the highest and lowest value in user-entered input?
(4 answers)
Closed 9 years ago.
Please help me in finding the Highest and Lowest number.
I swear, I did read countless posts on the site about this problem before I decided to post the code here, because all of them had known numbers of input.
I have "unknown" input from the user. It could be any given positive or negative numbers. I am totally blank now after trying it for almost a day. Any helps is Greatly Appreciated.
package test;
import java.util.Scanner;
import java.lang.*;
import java.io.*;
public class Test {
public static void main(String[] args){
int highest=Integer.MIN_VALUE;
int lowest=Integer.MAX_VALUE;
Scanner in = new Scanner(System.in);
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
if(n > highest){
lowest = highest;
highest = n;
}
if (n < lowest){
highest=lowest;
lowest=n;
}
System.out.println(highest);
System.out.println(lowest);
}
}
This is where your code is breaking.
highest=lowest;
lowest=n;
Now about initializing these variables.
How I, personally would start this program would be initializing both the lowest and highest with n. So you don't have to worry any bounds.
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
int highest = n;
int lowest = n;
for(int i = 0; i < 9; i++){
System.out.println("Enter any positive or negative number");
n = in.nextInt();
if(n > highest){
highest = n;
}else if (n < lowest){
lowest=n;
}
}
System.out.println(highest);
System.out.println(lowest);
This asks the user to input 10 different digits. then prints out the highest and lowest values.
else if (n < lowest) this could also be a else if because if n is the highest value it cant be also the lowest value because of my initialization at the start.
Why are you saving the lowest value in the highest value?
You should define a loop
Complete code:
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
if(n > highest){
highest = n;
}
if (n < lowest){
highest=lowest;
lowest=n;
}
}
System.out.println(highest);
System.out.println(lowest);
Related
When the for loop detects a number that is less than the positive integer inputted by the user and perfectly divisible, it prints it and that is because the for loop just continues counting through each number. However, I need it to prime factorize the positive integer inputted by the user.
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int Number = console.nextInt();
for (int counter =2; counter < Number; counter++) {
if (Number % counter == 0) {
System.out.print(" "+counter);
}
}
}
}
What you need to do to print all factors is to divide Number by counter when you've determined that counter is a factor. You also need to try counter again, in case there is more than one copy of a factor in a number, e.g. 12 is 2 * 2 * 3. Don't forget to print whatever Number is at the end, in case it didn't drop all the way to 1.
for (int counter = 2; counter <= Math.sqrt(Number); counter++) {
while (Number % counter == 0) {
Number /= counter;
System.out.print(" " + counter);
}
}
// Print what's left.
if (Number > 1) {
System.out.println(" " + Number);
}
As an aside, I've also changed the for loop condition to stop at the square root of Number, because for prime factor trials, if you've found a factor greater than the square root, then you should have found the corresponding factor that is less than the square root first.
Additionally, normal Java naming conventions would have you name the variable number in lowercase, to avoid confusion with classes such as java.lang.Number.
Your on the right track you just need to divide Number (num in the below code) by counter in the loop:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
System.out.printf("Prime factors of %d: %s%n", num, getPrimeFactors(num));
}
public static List<Integer> getPrimeFactors(int num) {
List<Integer> primeFactors = new ArrayList<>();
for (int counter = 2; counter <= num; counter++) {
while (num % counter == 0) {
primeFactors.add(counter);
num /= counter;
}
}
if (num > 1) primeFactors.add(num);
return primeFactors;
}
}
Example Usage:
Enter a positive integer: 12
Prime factors of 12: [2, 2, 3]
Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 0;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
I would like to be able to find the occurrence of the largest int, and I am not sure how to go about doing so, in a rather simple way. I tried adding occurrence++; under largest = number;, but that did not work.
For example, I would type 6 as input, and I would get random numbers 54, 74, 61, 89, 13, 89.
The desired output would be max is 89. Occurrence is 2.
Also, I am trying to only get the code to print only 10 numbers per line, then it would skip to the next line and continue.
In case of reoccurrence, increase occurrence variable;
set occurrence to 1 in case of new larger number
You can use
if(number > largest){
largest = number; // found larger value
occurrence = 1; // reset occurrence back to initial
}else if(number == largest){
occurrence++; // keep track of same large value
}
You need to use an else if condition to check equality like this
Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 1;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}else if(number == largest){
occurrence++;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
P.S - Initialize occurrence = 1 as there will be at least one time the largest number will be present
I think you are almost there. Basically, you are missing a check on whether the new random number is equal to the current largest number. Something like:
if (number == largest) {
occurrences++;
}
Also, remember to reset occurrences when a new largest number has been found:
if (number > largest){
largest = number;
occurrences = 1;
}
This question already has answers here:
Java program to find the largest & smallest number in n numbers without using arrays [closed]
(8 answers)
Closed 6 years ago.
I have a slight issue with my program. I need to ask the user to input as many numbers as they want and then the program will tell them what is the smallest and largest number. My issue is when all is said and done it prints out "the largest number is 0" and "the smallest number is 0". It always says that even if i never enter 0. I was wondering what was wrong with the program. Any pointers or helpers would be fantastic. Again to repeat, the issue im having is that the smallest and largest come back as 0's no matter what.
import java.util.Scanner;
public class LargestAndSmallest {
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the numer");
int n = keyboard.nextInt();
num = keyboard.nextInt();
while (n != -99) {
System.out.println("Enter more numbers, or -99 to quit");
n = keyboard.nextInt();
}
for (int i = 2; i < n; i++) {
num = keyboard.nextInt();
if (num > large) {
large = num;
System.out.println(large);
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is " + large);
System.out.println("the smallest is " + smallest);
}
}
I used this code as in the first place: Java program to find the largest & smallest number in n numbers without using arrays
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LargestAndSmallest {
public static void main(String... args) {
final Scanner keyboard = new Scanner(System.in); //init the scanner
System.out.println("Enter a number");
final Set<Integer> ints = new HashSet<>(); //init a set to hold user input
int n; //declare a variable to hold each number
while ((n = keyboard.nextInt()) != -99) { //loop until 99 is entered
ints.add(n); //add user input to our set
System.out.println("Enter more numbers, or -99 to quit.");
}
//output aggregate info
System.out.println("the largest is " + Collections.max(ints));
System.out.println("the smallest is " + Collections.min(ints));
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class
Right now for a Java course I'm trying to build a Mastermind-like game. In this game a 4-digit random number is generated, and the user tries to guess the number. With each guess the computer states how many correct digits are in the right order, and how many correct digits are in the wrong order.
For some reason, everything works up to my binary search for this program, which is really the heart of the program. I've spent hours tweaking it and I still cant get it. Any ideas?
In this example I'm trying to guess 9935, I realize that's not a random number though.
Thanks so much!
EDIT: When I run this program and use the guess "9875", it does not give me the right results.
The guesses and results I'm required to find are:
Please enter a four-digit number: 9874
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 1
Please enter a four-digit number: 9899
The number of correct digits but in the wrong place: 1
The number of correct digits in the right place: 1
Please enter a four-digit number: 9593
The number of correct digits but in the wrong place: 3
The number of correct digits in the right place: 1
Please enter a four-digit number: 9935
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 4
You are correct!
public class Mastermind {
public static void main(String[] args) {
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int randomNumber = 9935;
int[] randomArray = new int[4];
int temp = randomNumber;
for (int i = 3; i >= 0; i--){
int n = temp%10;
randomArray[i] = n;
temp /= 10;
}
boolean found = false;
while (found == false){
System.out.print(Arrays.toString(randomArray));
int[] guessArray = new int[4];
System.out.print("Please enter a four-digit number: ");
int guessTemp = input.nextInt();
for (int i = 3; i >= 0; i--){
int n = guessTemp%10;
guessArray[i] = n;
guessTemp /= 10;
}
if (Arrays.equals(randomArray, guessArray)){
System.out.println("You are correct!");
found = true;
} else {
int numberRightRight = 0;
int numberRightWrong = 0;
int indexFound = 0;
for(int i = 0; i < guessArray.length; i ++){
System.out.println(randomArray[i]);
indexFound = Arrays.binarySearch(guessArray, randomArray[i]);
System.out.println(indexFound);
if (indexFound >= 0){
if(indexFound == i){
numberRightRight++;
} else {
numberRightWrong++;
}
}
}
System.out.println("The number of correct digits but in the wrong place: " + numberRightWrong);
System.out.println("The number of correct digits in the right place: " + numberRightRight);
}
}
}
If you are not required to use Arrays.binarySearch(int[], int) you could use your own simple lookup method for an unsorted Array:
public static int findInArray(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
now instead of calling Arrays.binarySearch(guessArray, randomArray[i]); just call findInArray(guessArray, randomArray[i])