Question by vioe: Help with basic programming – “while” and “for” statements?
How can I write a java program that will take two POSITIVE integers (x and y) from user (if user types in neg numbers, the program will end itself), and then displays the result of adding the x integer for y times.

For example :

=============
>Enter a positive integer: (user will type number such as 5)

>How many times you want to add this number together?: (user will type another positive integer here such as 3)

>The answer is 5 + 5 + 5 = 15
>Bye!

(If user types in negative integer by accident, the program will display an error message such as “Error: It has to be a positive number!” and end)

this program will have to use “while” and “for” loops…please help
THIS IS ALL I CAN THINK OF :(…i still cant figure out how to include while or for statements…PLEASE HELP

import java.util.Scanner;

public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int num1, num2, sum;

System.out.println(“=============================”);
System.out.println(“Violetta Egorova , 1501007361”);
System.out.println(“=============================”);
System.out.println(“Assisgnment #4”);
System.out.println(“=============================”);

System.out.print(“Enter a positive integer: “);
num1 = input.nextInt();

if (num1<0) { System.out.println("Error: It has to be a positive number!"); } System.out.print("How many times you want to add this number together?"); num2 = input.nextInt(); if (num2<0) { System.out.println("Error: It has to be a positive number!"); } } } } everytime i compile it, an error says somethings wrong with the class name..but i have no idea what...and when i try to run the prog, it just says it cant find it...i really need to get this done... Best answer:

Answer by Daniel R
OK, this is obviously homework. How will it help you if we do it for you? It obviously won’t help you learn to program.

If you want to have a go, and post what you have, we’d be happy to offer suggestions. But we won’t do your homework for you.

Add your own answer in the comments!

One thought on “Help with basic programming – “while” and “for” statements?”

  1. import java.io.*;
    class Basic
    {
    public static void main(String args[])throws IOException
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print(“Enter a positive number : “);
    int n=Integer.parseInt(br.readLine());
    if(n<0)
    {
    System.out.println("Error : it has to be a positive number");
    System.exit(0);
    }
    System.out.print("How many times you want to add this number together? : ");
    int times=Integer.parseInt(br.readLine());
    System.out.print("The answer is ");
    for(int i=1;i<=times;i++) { System.out.print(n); if(i

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.