I am trying to make a program that takes positive integers from the user and finds the maximum until the user enters a negative number. I have to use a do while loop. It won't accept the variable in the while part of the statement. I don't understand why this is, because I checked and I should have the correct amount of brackets.
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
do {
int currentnumber = 1;
int number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
}
if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
Edit: Once I fixed the number issue. The program will print "Enter a number: " but when a number is entered it doesn't do anything
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number){
currentnumber = number;}
if(number > currentnumber){
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
}while(number > 0);
}
}
declare number outside of do block so that while() can access it
No, because in Java, local scopes are defined by {}(block). If you declare number inside the do block, it won't be accessible outside.
Notice that the condition (number > 0) is outside of the do block.
What can you do? You can declare number before the do-while:
int number = ...;
do {
...
} while (number > 0);
To use a variable in the conditional part of a do-while loop, the variable must have scope outside the loop--it must be defined outside the loop.
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
} if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
This is no different from any other loop.
while (number > 0) {
int number;
// do stuff
}
That loop will have obvious problems. But if we rewrite it to:
int number = 1;
while (number > 0) {
// do stuff
}
The problems are gone.
The same logic applies to your do-while loop.
You declared number inside the loop and it therefore only exists within the loop. In order to use it outside of the body of the loop (which includes the loop's conditional statement), it must be declared outside the loop.
One thing I noticed is that you are setting currentnumber in both less than and greater than cases. If you are attempting to determine the max input value then you only need to assign that value if it is greater than the current max value.
One other reason it "doesn't do anything" is likely because the number you have entered is less than the currentnumber. In that case your program doesn't output anything but goes back to accepting input.
Also consider moving the output asking the user for input within the loop. Then each iteration will re-prompt the user for input.
Scanner in = new Scanner(System.in);
int currentMax = 0;
int number = 0;
do {
System.out.println("Enter a number: ");
number = in.nextInt();
if(number > currentMax) {
currentMax = number;
System.out.println("Max number is: " + currentMax);
}
} while(number > 0);
Related
import java.util.*;
public class happy_number
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = in.next();
for (int i = 0; i < num.length(); i++){
double index = num.charAt(i);
(double)index = Math.pow((double)i,2);
System.out.println(index);
}
}
}
For some reason, the second line in the for loop is returning as unexpected type– required: variable found: value. Any insight?
error: image of the error
It doesn't continue to ask you for an input. What is happening here is that the execution get's struck in an infinite loop, for certain types of inputs (in this case non-magic numbers).
For Eg.:
Let's take the example 44, below will be the values for each iteration in the for loop.
num
num1
num2
Start
44
-
-
After 1st iteration
8
4
4
After 2nd iteration
8
8
0
After 3rd iteration
8
8
0
…
…
…
…
We can see that the execution get's struck in the loop.
You have to exit out of the loop when you get such inputs.
One way to exit out of the loop is to add a condition in the for loop.
Another way is to add an if statement inside the for loop, and exit out of the loop based on the condition.
You have to decide what condition you should use in order to exit the loop, based on your problem statement.
Look on to the loop and the value populated inside. There is no breaking condition found and the correct test for a magic number:
A simple code:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int n = num;
while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");
}
I am trying to take 10 integers from the user's input and find the minimum and maximum using for loop. But my final print statement just prints the list of numbers entered. I'm lost.
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
double a = 0;
double max = 0;
double min = 0;
System.out.print("Enter ten floating points: \n");
for(a=0; a <10; a++) {
a=scan.nextDouble();
if(a == 0) {
min=a;
max=a;
}
else if(a < min) {
min=a;
}
else if (a > max){
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
Issue is in your for loop change it to
for (int x = 0; x < 10; x++) {
there is another issue, you need to change
if(a == 0){
To
if (x == 0) {
Try this
Scanner scan=new Scanner(System.in);
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for( int i=0; i<10 && scan.hasNextInt(); i++ ) {
int next = scan.nextInt();
maximum = Math.max( next, maximum);
minimum = Math.min( next, minimum);
}
System.out.println("Found maximum :"+maximum+", minimum:"+minimum);
scan.close();
First, we create the scanner.
Next, we set a value for your maximum - since integers can be negative, we can not use 0, but have to use the smallest possible integer.
Same for minimum.
In the for loop, we have to make sure that we terminate the loop after 10 iterations, or if the input stream does not have any more int's.
Next, we use the mathematical function max to find out which number is largest - the previously found maximum, or the next int from the Scanner.
And same for minimum.
Finally, remeber to close the Scanner, to avoid resource leakage.
First your code should not run correctly since you use the same variable a as the counter and as the variable to store user input. You should use two different variable.
Second declare your variable that store the input from user inside the loop, otherwise it may keep the value from the previous loop.
Third your if(a == 0) condition will reset min and max when the user enter the number 0. Which is not what you want.
Finally you should not initialize max/min like that. By defining min as 0, if the user enter only positive number the min will be 0 but the user never entered 0. You instead initialize them at the first entry from user.
This should look like this :
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
System.out.print("Enter ten floating points: \n");
double tmp = scan.nextDouble(); //read first number from user
double max = tmp; //intialize with the first input
double min = tmp;
for(int i=0; i <9; i++) { //from 0 to 8, 9 numbers since the first has already been read
double a = scan.nextDouble(); //at every loop read a number from the input
if(a < min) {
min=a;
}
//removed else since max and min are independant
if (a > max) {
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
This is what I have so far. I am supposed to write this code with a For loop and if/else statement, but /i am stuck on how to do it properly. It would be nice if someone can tell me how to properly use a For loop and if/else statement together instead of giving the answer:
import java.util.*;
public class SumEvenOdd
{
public static void main(String []args)
{
Scanner keyboard= new Scanner(System.in);
int counter;
int i= 0;
int num=0;
int sumOdd= 0;
int sumEven= 0;
System.out.println("Enter integers other then Zero: ");
num=keyboard.nextInt();
System.out.println("The numbers you entered are: ");
for (i =num; i !=0; i=i)
{
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
i = keyboard.nextInt();
}
System.out.println("Even sum: " + sumEven);
System.out.println("Odd sum: " + sumOdd);
}
}
Your loop never executes because your loop condition is false to begin with:
for (i =num; i !=0; i=i) // i already equals 0 so i != 0 equates to false
You also aren't incrementing or decrementing with i=i so even if your condition was true you'd be stuck in an infinite loop. Use i++ to increment the value of i by 1 in each iteration of your for loop.
Also, you're only taking in one number from the user. One simple way of handling this would be to first ask the user how many numbers they want to enter first, then use that input to loop that many times asking for the numbers to sum. For example:
System.out.println("How many numbers do you want to enter? ");
num=keyboard.nextInt();
int[] addThese = new int[num]; // create an array of size num to store numbers
for(int i = 0; i < num; i++) {
System.out.print(": ");
addThese[i] = keyboard.nextInt();
}
// now use your for loop to iterate over addThese[] and find your sums
...
EDIT
You've confused yourself (and me) with your print statements and lack thereof. Your program runs fine but I don't think you're realizing it because of this.
Add something like this inside your loop so you know it's waiting for input:
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
System.out.print(": "); // <-- let the user know you're expecting more input
i = keyboard.nextInt();
You can use an array like I used above to store the user input so you actually can tell the user what numbers they entered.
In your application you do not need a for loop as you are breaking the loop as long you dont enter 0.
for loops is used to iterate through collections (for each loop) or iteratively increment a counter till it satisfies the break(classic for loop).
A do while(i!=0) loop would be more appropriate in your scenario.
If you want the answer in while loops
import java.util.*;
/*
EXPLANATION
Question: write a program that reads a set of integers and tells the sum of the even and odd numbers
First: Initialize 4 variables(all integers)
Second: Take input and print title
Third: Take a while loop that will run when i is smaller than a
Fourth: take inputs of the numbers and check for condition od or even and add the numbers
Fifth: Break the while loop if input =
*/
public class EvenOddSum
{
public static void main(String[]args)
{
//initializing variables
int InputNums = 0, OddNums = 0, EvenNums = 0, loopingVar = 0, PrintAmount;
//initializing scanner class
Scanner scanner = new Scanner(System.in);
//Input using Scanner
System.out.print("How many numbers you want to input: ");
PrintAmount = scanner.nextInt();
//Loop to execute if PrintAmount is bigger than or equal to The loop Variable
while(loopingVar <= PrintAmount)
{
//increase Loop Variable by 1 if it is smaller than PrintAmount
loopingVar++;
//The input which will be sorted into odd or even
System.out.print("Please input a number : ");
InputNums = scanner.nextInt();
//Conditional statements to Sort Input into Odd or even
if (InputNums % 2 == 0)
{
//store input numbers into OddNums var if it is not divisible by 2
OddNums = OddNums + InputNums;
}
else
{
//store input numbers into EvenNums var if it is divisible by 2
EvenNums = EvenNums + InputNums;
}
if(loopingVar == PrintAmount)
{
//If the loop variable is equal to the print amount the break will end the loop
break;
}
}
//if the condition is true the sums are printed and the code is stopped
if (loopingVar == PrintAmount)
{
System.out.println("Sum of even numbers is : " + OddNums);
System.out.println("Sum of odd numbers is : " + EvenNums);
System.exit(0);
}
//if InputNums is smaller than 0 there has been some error in the code
if (InputNums < 0)
{
System.out.print("Invalid input");
System.exit(0);
}
}
}
Scanner input = new Scanner(System.in);
int num;
int i;
int x = 0;
int y = 0;
System.out.print("How many numbers you want to input: ");
i = input.nextInt();
for (;;) {
i--;
System.out.print("Please input a number : ");
num = input.nextInt();
if (num % 2 == 0) {
x = x + num;
} else {
y = y + num;
}
if (num < 0) {
System.out.print("Inivald input");
System.exit(0);
}
if (i == 0) {
System.out.println("Sum of even numbers is : " + x);
System.out.println("Sum of odd numbers is : " + y);
System.exit(0);
}
}
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// printing the sum of even and odd number input from the user
int evensum = 0 ;
int oddsum = 0 ;
System.out.println("Enter the number:");
for(int n1= sc.nextInt(); n1>0; n1=sc.nextInt()) {
if(n1 % 2 == 0) {
evensum+=n1 ; // evensum = evensum + n1 ;
}
else {
oddsum+=n1 ; // oddsum = oddsum + n1 ;
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
// asking for continuing y or n?
System.out.println("Do you want to continue ? yes = 1 or no = 0");
int choice = sc.nextInt();
if(choice==1) {
System.out.println("Enter the number :");
}
else {
System.out.println("End");
break;
}
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
}
}
This is the code that I have attempted, I can get the 5 integers into the array but my problem is validating that input and giving an error message when it is not. If I put in the 5 integers and they are in the required range it works and when I input a number that is not in the required the range I get an error message which is what I want but if I enter a symbol or letter my program crashes.
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
You should check that the user inserts an int before assuming so (scanner.nextInt();).
You are using scanner.nextInt(); so it is expected that the text entered will be int and if you enter other then int it will throw exception
I would use scanner.nextLine() and then try to convert String into int with NumberFormatException check:
int value;
String input = scanner.nextLine();
try {
value = Integer.valueOf(input);
} catch (NumberFormatException ex) {
System.out.println("Number format exception");
continue;
}
if (value >= 0 && value <= 20)
...
If you are doing Q1 for C2 paper in DCU than its the Sum total you display at the end not the average. I was going to do add another While loop after the scanner.nextint() to test the input is a valid integer. The 3 validations would be is number an integer and is it in range and the number of integers to be entered to the array is 5. I am thinking very similar to you, its adding the extra check and where is goes in the sequence.
import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}