public class javapractice14
{
public static void main(String[] args)
{
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
Scanner console = new Scanner(System.in);
System.out.println("Please enter desired amount of numbers (-1 ends program)");
for( int number = console.nextInt(); number != -1; number = console.nextInt()); //Enter -1 to end program
{
I am receiving my error below saying it cannot find the symbol: variable number
I believe number was declared in the for loop, was it not declared there? I've tried declaring "int number;" outside the loop, but it ends with the same results. I used: What do I have to do to display the largest and the smallest number using a loop? as a reference for helping me solve part of this.
largest = number > largest ? number : largest;
smallest = number < smallest ? number : smallest;
}
System.out.println("Your largest number is: " + largest);
System.out.println("You smallest number is: " + smallest);
}
}
for( int number = console.nextInt(); number != -1; number = console.nextInt()); <--see there is a semicoln at end of your for loop it means loop end from there
so you can't refer to block variables declared inside the for loop from outside the loop. That is why you get that compile error
remove that semicoln. Then it must work fine
for( int number = console.nextInt(); number != -1; number = console.nextInt()){ // no semicol at the end
// your logic
}
// print your numbers
Related
Should receive an output of the largest/smallest numbers within the inputs, what seems to be the problem? I have tried looking it up online, the source code appears to be the same. Thank you for your assistance.
Source code:
package counting.largest.smallest;
import java.util.Scanner;
public class CountingLargestSmallest {
public static void main(String[] args) {
Scanner TheN = new Scanner(System.in);
int counter = 0;
int number;
int smallest = Integer.MIN_VALUE;
int largest = Integer.MAX_VALUE;
while (counter < 10) {
System.out.print("Integer=");
number = TheN.nextInt();
counter++;
if (number < smallest) {
number = smallest;
} else if (number > largest) {
number = largest;
}
}
System.out.println("\nSmallest=" + smallest);
System.out.println("Largest=" + largest);
}
}
Output:
Integer=1
Integer=2
Integer=3
Integer=4
Integer=5
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=-2147483648
Largest=2147483647
there were 3 bugs:
1.
int smallest=Integer.MIN_VALUE;
int largest=Integer.MAX_VALUE;
number=smallest;
number=largest;
Using else if
1: When you want to find a min number keep it Integer.MAX_VALUE and when you want to find max keep it has Integer.MIN_VALUE.
Why for min we Initialize Integer.MAX_VALUE and for max we Initialize Integer.MIN_VALUE?
Say you want to multiple n numbers from the user. So we will declare and initialize mul variable to 1. cause we know any number multiple by 1 will give us the same number.
Whereas if we initialize mul with 0 it will give us 0 only.
So we say 1 for multiplication is identity.
Similarly, for finding Minimum number we use an identity that is Integer.MAX_VALUE.
So that number that less then Integer.MAX_VALUE are saved in Samllest variable.
int smallest=Integer.MAX_VALUE;
Similarly for max we initialize it with Integer.MIN_VALUE SO that number that are greater then Integer.MIN_VALUE are stored in largest variable.
int largest=Integer.MIN_VALUE;
2: You are assigning number variable the value of smallest and largest it should be like smallest=number and largest=number
when you write x=0 it says x is 0 that means x is changed, Similarly when you write number=smallest its number = Integer.MAX_VALUE and smallest is not changing at all.
So you should write like smallest = number, It means smallest is the number and smallest is changing every time condition satisfies.
3: When you write
if(condition){
}else if(conditon){
}
else if is only excuted when first if statement if false and if first condition is true second if is never executed.
if we have descending number then second if will never be excuted which would result in having Integer.MIN_VALUE in largest variable.
And here you want to check for both min and max so we should have indepent if statement for each
if(condition){
}
if(condition){
}
Code:
Scanner TheN= new Scanner(System.in);
int counter=0;
int number;
// changed
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
while(counter<10){
System.out.print("Integer=");
number=TheN.nextInt();
counter++;
if(number<smallest){
// changed
smallest= number;
}
if(number>largest){
// changed
largest=number;
}
}
System.out.println("\nSmallest="+smallest);
System.out.println("Largest="+largest);
Output:
Integer=1
Integer=2
Integer=2
Integer=4
Integer=3
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=1
Largest=10
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
Hey guys I need help with this assignment. When I run what I have it just loops forever, help would be much appreciated. Here's what my assignment is:
Write a program segment on the following page which reads a sequence of integers from the keyboard until 0 (zero) is entered. As it is entered print each integer (except for the 0 that stops the program) and at the average of the integers entered.
Each non-zero integer is printed on a separate line.
this continues until a zero is read, at which point the segment stops.
Here's what I have so far:
import java.util.Scanner;
public class List {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int boom = 0;
int sum = 0;
double average = 0;
int count = 0;
System.out.println("Enter a nonzero integer, please!");
boom = keyboard.nextInt();
while (boom != 0) {
sum += boom;
count++;
average = ((double) sum) / count;
System.out.println("The average is " + average);
}
}
}
You read the keyboard input only once. That's what you should do:
while (boom=keyboard.nextInt() != 0) {
sum += boom;
count++;
average = ((double)sum) / count;
System.out.println ("The average is " + average);
}
It will loop forever if you enter a non-zero integer at the boom=keyboard.nextInt() stage. The reason why is that boom never changes in your while block and the condition for stopping is that boom does not equal zero.
You'll need to set boom to a non-zero value outside of the loop and move your assignment to boom of the int from the keyboard inside the loop.
I thought my code was correct but when I ran it, my output statements at the bottom wouldnt produce. I'm asking the keyboard to enter any number and then to end by entering -1. My while loop includes adding numbers, creating a sum, as well as giving the amount of even numbers. When I test my code I've been entering just 1,2,3,4 hoping to produce 4 total numbers. 2 even, and a sum of 10. Why isnt' my code getting to the print statements?
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a number. Enter -1 to stop program.");
int num = sc.nextInt();
int counter = 0;
int even = 0;
int sum = 0;
while (num != -1)
{
counter += 1;
sum += num;
if (num%2 == 0)
{
even +=1;
}
}
System.out.println("You have entered "+ counter + "number(s)");
System.out.println("You have entered "+ even + "even numbers");
System.out.println("The sum for the numbers you entered is "+ sum);
}
You never get the input again so the loop runs infinitely. You need to get the value again.
while (num != -1)
{
...
num = sc.nextInt();
}
num gets set before you enter the loop.
So, when does the num change inside the while loop? It doesn't. That's why your code won't exit the loop.
I suggest moving the
num = sc.nextInt();
inside the loop.
I'm writing a program for homework that is supposed to read in an unspecified number of 0-100 scores (maximum of 100 scores) and stop after -1 or any negative number is entered.
I've put this into a Do While loop that is set to terminate when -1 is pulled in through Scanner. The loop has a counter that keeps track of how many times the loop has been gone through, an adder that adds all the input lines together to later compute an average, and a means to send the input value to an array after it has checked to see if the number is -1.
Instead of doing this, the loop only increments the counter every 2 loops and -1 will only terminate the loop on an even cycle number, other wise it will wait until the next cycle to terminate. This completely baffles me, I have no idea why it's doing this. Could someone point out the error? Thanks in advance! This is all I have so far.
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while ( CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
You are calling twice In.nextInt(), i.e., you are reading two lines in each loop iteration.
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;
Use this instead.