Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have the following error
cannot find symbol: variable num
in all the if statements.
This is my current code.
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
do{System.out.println("Type a number (or -1 to stop): ");
int num = console.nextInt();
}while(!num == -1);{
System.out.print(+ num );
}if (min < num) {
num = min;
}if (num > max) {
max = num;
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
}
Help.
The issue lies with the scope of the variable num. You have declared it inside the do block so num will not be accessible outside the do block. Also, your if condition is not correct.
Implement this and the code should run just fine:
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = 0;
do{
System.out.println("Type a number (or -1 to stop): ");
num = console.nextInt();
} while(num != -1);
if (min < num) {
num = min;
} if (num > max) {
max = num;
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
You want to test for max and min inside the loop and not after it terminates, since that means that you are only testing the last number that was entered – which will always be -1 (minus one). You also write that you want to ignore the -1. I believe the following code does what you require – which is to find the minimum and maximum of a series of numbers that are entered by the user.
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = 0;
do {
System.out.print("Type a number (or -1 to stop): ");
num = console.nextInt();
console.nextLine();
if (num != -1) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
} while (num != -1);
if (max == Integer.MIN_VALUE) {
System.out.println("No numbers were entered.");
}
else {
System.out.printf("max = %d , min = %d%n", max, min);
}
Note that you need to consume the <ENTER> key that the user presses after entering each number. Hence the call to method nextLine() of class Scanner. Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
If the first number entered is -1 then the user did not enter any numbers and therefore there will be no maximum or minimum. If the first number entered is -1, then the value of max will be Integer.MIN_VALUE.
Syntax problem
while (!num == -1);{
Won't work, because Java does not allow an negate operator (!) to be at the start of a non-type boolean. You cannot do a local-body at the while loop within a do-while loop.
The fix here
You can fix your code by simply changing this line to:
while (num != -1); {...}
Therefore you have to remove the whole while body and replace it with
while (num != -1);
So removing the bracket
I highly recommend you to learn the Java syntax.
Sincerly, Vinzent
Related
Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);
Im new to programming and am stumped on this problem, Ive tried a few different ways with no success.
Implement (source code) a program (name it LargestOccurenceCount) that read from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the loop). The program should ignore any negative input and should continue to read user inputs until 0 is entered. The program should display the largest value and number of times it appeared
Scanner reader = new Scanner(System.in);
int num = 0;
int array[] = null;
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
array[num] = num;
}
Sample run 1:
Enter positive integers (0 to quit): 3 4 5 -9 4 2 5 1 -5 2 5 0
Largest value: 5
Occurrences: 3 times
The program should output the largest value entered and the number of times it was entered before 0 is entered.
You can use the following snippet:
// part of reading the values from command line and
// putting them into this array is omitted
int[] array = ...;
int biggest = 0;
int occurance = 0;
for(int num : array) {
if(num > biggest) {
biggest = num;
occurance = 0;
}
if(num == biggest) {
occurance++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
As mentioned in the comment, I've omitted the part where you read the values from the command line, as that doesn't seem to be your problem.
Another solution which does the reading directly, and without the need of an array and all inside one loop:
Scanner scanner = new Scanner(System.in);
int biggest = 0;
int occurance = 0;
int num;
while (true) {
System.out.print("Enter a number: ");
// this may throw an Exception if the users input is not a number
num = Integer.parseInt(scanner.nextLine());
if(num == 0) {
// user entered a 0, so we exit the loop
break;
}
if(num > biggest) {
biggest = num;
occurance = 1;
} else if(num == biggest) {
biggest++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
Split your problem into two parts.
1. Find the largest value
int findLargest(int[] array) {
assert array.length > 0;
int result = array[0];
for (int element : array) {
if (element > result) {
result = element;
}
}
return result;
}
... and find it in the array
int countOccurences(int[] array, int value) {
int occurences = 0;
for (int element : array) {
if (element == value) {
occurences++;
}
}
return occurences;
}
Note that array should have at least one element;
If there is no requirements to use array only, you can use ArrayList for storing user inputs
List<Integer> list = new ArrayList<>();
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
list.add(num);
}
Then if you are good with stream api, there is quite concise solution:
Map.Entry<Integer, Long> lastEntry = list.stream()
.collect(groupingBy(Function.identity(), TreeMap::new, counting()))
.lastEntry();
System.out.println(
"Largest value: " + lastEntry.getKey() +
" Occurrences: " + lastEntry.getValue() + " times");
I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.
So my code works in all test cases except for when there are only two integers.
Example if user inputs: terminating number as -1 and then inputs 1,2 and then -1 again the smallest numbers are 1,1 and not 1,2
Terminating number is just the way to end the sequence/program.
public static void main(String[] args) {
double num;
double min = 0;
double min2 = 0;
System.out.println("Enter terminating value:");
int term = IO.readInt();
System.out.println("Enter next value:");
num = IO.readDouble();
if(num == term){
IO.reportBadInput();
main(args);
}
int count = 0;
min = num;
min2 = num;
do{
num = IO.readDouble();
if(num!= term && num < min) {
min2 = min;
min = num;
}
else if (num!= term && num < min2) {
min2 = num;
}
count++;
}while (num != term);
if(count < 2){
IO.reportBadInput();
main(args);
}
else{
IO.outputDoubleAnswer(min);
IO.outputDoubleAnswer(min2);
}
}
The issue with your code lies in setting both minimal values to the number that was first entered. This is bad because if the user enters the smallest value first, both min and min2 already contain the minimum value. That means the condition input < min2 is always false, causing min2 to always contain the value the user has entered first.
To fix this, simply set the value of min2 to a value which is larger than any other value the user could enter (for example Double.MAX_VALUE or Double.POSITIVE_INFINITY).
Just as a hint concerning the error-handling part of your code: if you call main again after reminding the user that their input was invalid, make sure to add a return behind that call or the execution will continue after the called main method is finished. Something like this:
if (count < 2) {
IO.reportBadInput();
main(args);
return;
}
for these guidelines:
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, separated by a space and on a single line, the sum of all the even integers read and the sum of all the odd integers read. Declare any variables that are needed.
ASSUME the availability of a variable, stdin , that references a Scanner object associated with standard input.
I wrote this code, but it the HW software will not except it due to a logical error. I cant seem to find the logical error here. can someone point out what is wrong with it?
int sumP=0;
int sumO=0;
Scanner stdin = new Scanner (System.in);
System.out.println("enter an odd or even number");
while (stdin.nextInt() >= 0){
if(stdin.nextInt()%2 == 0)
sumP+= stdin.nextInt();
else
sumO += stdin.nextInt();
}
System.out.println(sumP + " " + sumO);
You need to save the value you have read, otherwise you will be used different values in the while loop and the addition.
int n;
while((n = stdin.readInt()) >= 0) {
// use the same value of n
This worked for myprogramminglab - Java
int sum=0;
boolean areMore = true;
int negative;
while (areMore)
{
int number = stdin.nextInt();
if (number <= 0)
areMore = false;
else if (number %2 ==0 )
sum = sum + number;
else
negative = sum + number;
}
System.out.println(sum);
int number = 1;
while (stdin.hasNextInt() && number > 0)
{
number = stdin.nextInt();
if (number % 2 == 0 && number > 0)
System.out.print(number + " ");
}
The answer to this and many other codelab exercises can be found at Java Codelab Solutions