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");
}
Related
I have to create a program that gets a range from the user then adds each even number in the range and prints to screen. I am struggling to figure out how to add each number in the for loop. If the range is 5 to 10 the screen should print 24 as the answer. Below is my code.
//worksheet 4 - question 3
//asks user for a range. Adds even numbers in range and prints their sum.
import java.util.Scanner;
class P3LoopRange
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int initial, finalValue;
System.out.print("Enter a start value: ");
initial = input.nextInt();
System.out.print("Enter a second value: ");
finalValue = input.nextInt();
while (finalValue <= initial)
{
System.out.println("Second value must be larger than start value.");
System.out.print("Enter a second value: ");
finalValue = input.nextInt();
}
int range = finalValue - initial;
int x = 0
for (int i = initial; i <= finalValue; i++)
{
if (i%2==0)
{
int x = x+i;
}
}
System.out.printf(x);
}
}
You declare twice the x local variable.
You cannot as it is not legal to have a duplicate local variable.
Besides, declaring it inside the loop makes it be overwritten at each iteration.
So, just declare it before the loop and it should be fine.
int x = 0;
for (int i = initial; i <= finalValue; i++)
{
if (i%2 == 0)
{
x = x + i;
}
}
Change int x = x+i; to x=x+i;. Here you are re initializing x each time.
Problem is at: int x = x+i;
just remove int and your problem is solved
Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);
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);
}
}
I'm writing a program that adds the first ten odd numbers, and gets the sum at the end.
Here is my code so far. My code reads the odd number in a list of 10 numbers. I want my code to be able to read 10 odd numbers even if there are more than 10 numbers entered. I know the problem is i < 10, which makes the program stop after the 10th number.
import java.util.Scanner;
public class question14
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i = 0;
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
}
}
Wrap it in a while loop instead.
While oddnumbers < 10 ask for a new number.
int i = 0
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
EDIT:FULL CODE
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stevengreen22
*/
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int input;
int inputCount = 0;
while (i < 10){
//Having this inside the while loop prompts the user every time.
System.out.println("New number?");
input = scan.nextInt();
inputCount++;
if(input % 2 == 1){
sum += input;
i++;
}
}
System.out.println("sum: "+sum);
System.out.println("Number of odds:" + i);
System.out.println("Numbe of inputs: " +inputCount);
System.out.println("Average cos I miss typing sout tab:" + (inputCount/sum));
}
}
The principle thing is that you don't know how many numbers the user is going to enter into the program, so you want to use a while loop instead of a for loop.
One chooses a for loop when they know how many elements they want to iterate over; one chooses a while loop when they don't know how many elements they'll need to iterate over.
You'll need to define another variable called counter outside of the loop, and use this as your loop variable constraint.
while(counter < 10) {
// loop
}
You'll also need to update counter whenever you encounter an odd value.
This should work
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i=0;
while (i<10){
odd=keyboard.nextInt();
if (odd%2!=0){
sum=sum+odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is "+sum);
}
Just replace your for loop with a while loop and track the number of odd numbers in an integer:
int oddNumberCount = 0;
int inputNumber;
while(oddNumberCount<10)
{
inputNumber = keyboard.nextInt();
if(inputNumber%2!=0)
{
sum = sum+inputNumber;
oddNumberCount++;
}
}
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");
}