In: Computer Science
Please create using only For loops, as simple as possible as I am attending Java1
Create two Java programs that do the following:
a. Use a for loop to print the numbers below on a single line as shown.
1 2 4 8 16 32 64 128.
b. Ask the user to enter numbers using the for loop. First ask the user how many numbers they will be entering in. Print the sum and average of the entered numbers.
c. Write a program that is a salute to pets. Ask the
user three questions:
* What is the name of your favorite pet?
* How many times would you like to see the name appear on the
screen?
* Would you like to see the names one per line, or arranged
horizontally?
Using a for loop, write a program to accomplish task the task above. Put in an error trap to guarantee that the user does not enter a negative number for the number of times the name is to appear. You could assume that the numbers are going to be integers.
For part a and b.
Code:
Output:
For part c:
Code:
import java.io.*; // imports all class from java.io
package
import java.util.Scanner; //scanner class found in java.util
package
public class Main
{
public static void main(String[] args) {
int d,i; // variable declaration
String name,f; //variable declaration
Scanner sc1= new Scanner(System.in);//Declaring sc1 as
an object of scanner class
Scanner sc2= new Scanner(System.in);//Declaring sc2 as
an object of scanner class
System.out.println("What is the
name of your favorite pet?");
name=sc1.nextLine();//input
System.out.println("How many times
would you like to see the name appear on the screen?");
d=sc1.nextInt();//input
System.out.println("Would you like
to see the names one per line, or arranged horizontally?");
f=sc2.nextLine();//input
if(d>0)
{
if(f.equalsIgnoreCase("one per
line")) //compares two strings irrespective of case
{
for(i=0;i<d;i++)
{
System.out.println(name); //
display
}
}
else
if(f.equalsIgnoreCase("horizontally")) //compares two strings
irrespective of case
{
for(i=0;i<d;i++)
{
System.out.print(name+"\t"); //
display
}
}
else{
System.out.println("Enter a valid
input"); // for invalid input
}
}
else{
System.out.print("Enter a valid input"); // for
invalid input
}
}
}
Output: