For Loop Sum Between Two Integers

Sep 28, 2014

I need to write a class in that uses the For loop and does the following things: asks user to input two integers, the second larger than the first. Next, use a for loop to sum the numbers between the two integers, including the original integer. For example: 5&8 would be 5+6+7+8 and lastly prints out the sum of this.

I have successfully been able to do the first part but when it comes to the For Loop I am a bit lost here is what I have so far

import java.util.Scanner;
public class Question3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an integer");
int num1 =sc.nextInt();
System.out.println("please enter a larger integer");
int num2=sc.nextInt();
int sum=0;
for(int i=num1; i<=num2;i++);
}
}

View Replies


ADVERTISEMENT

Loop To Add Integers From 1 To 50?

Mar 11, 2014

Create a loop where you add the integers from 1 to 50.

public class Sum50 {
public static void main(String[] args) {
int sum = 0;
int max = 50;
for(int i = 0;i <= max; i++){
sum=sum+i;
}
System.out.println("Sum is " + sum);
}
}

View Replies View Related

For Loop - Integers Stuck At 0

Oct 6, 2014

I have this code running correctly in Eclipse all except that it seems no matter where I declare, highest, lowest, average they always seem to stay at "0". I have a feeling the location of the Initialization is not the error since I have tried moving it to inside differ loops.

Stipulations on writing this code are:

Note: You do not need to use array to save each input score for this lab. A Single loop to read in each grade, compare with the current highest grade, lowest grade, and calculate the running sum at the same time.

import java.util.Scanner;

/*Write a program that prompts the user to enter the total number of students first.
*Then ask the user to input each student’s grade and use loop statements to read in each grade.
*Check input grade to make sure 0<=grade<=100, if the user input any other number, print out warning message and ask the user to input a new grade. Display the highest score, the lowest score and the average.
*/

public class LoopStatements {
// Main Method
public static void main(String[] args) {
// Initialize
int grade = 0; // grade value

[Code] ....

View Replies View Related

While Loop Involving Odd And Even Integers

Oct 9, 2014

My instructions are to:

1. Prompt the user to input two positive integers: firstNum and secondNum (firstNum must be smaller than secondNum).
2. Output all the even numbers between firstNum and secondNum inclusive.
3. Output the sum of all the even numbers between firstNum and secondNum inclusive.
4. Output all the odd numbers between firstNum and secondNum inclusive.
5. Output the sum of all the odd numbers between firstNum and secondNum inclusive.

*Use while loop
int firstNum, secondNum;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer: ");
firstNum = keyboard.nextInt();

[Code] ....

What to do with the while loop and how to find even and odd numbers.

View Replies View Related

Creating A Loop For Counting Integers

Jul 16, 2014

working on assignment to count the total integers and have a seperate system.out if a non integer.

import java.util.Scanner;
public class CountInteger {
public static void main(String[] args) {
int correctCount = -1 ; // count number of integers
int data;
int sum = 0;

[code]...

View Replies View Related

Loop / Boolean - Find Greatest Common Divisor Of Two Integers

Sep 25, 2014

In attempting to find the greatest common divisor (gcd) of two integers, n1 and n2, whereas k is a possible gcd and gcd is initialized to 1, the following code has been entered:

for (int k = 2; k <= n1 && k <= n2; k++) {
if ( n1 % 2 == 0 && n2 % 2 == 0)
gcd= k;
}

When asked to change the previous line of code to this:

for (int k = 2; k <= n1 / 2 && k < n2 / 2; k++){

the questions states this revision is wrong and to find the reason.....well, I've changed it, entered "3" (per the answer key) for n1 and n2....

now I can see logically where k (2 in this example) is not <= n1/2, which is 3/2 or 1, since we're dealing w/integers, yet when I compile and run, my answer is indeed, gcd = 1. However, since this is a Boolean expression where && is being used, since the first portion evaluates to "false", the 2nd portion isn't executed and thus my result of 1?...... loops are throwing me for one, for sure....

View Replies View Related

Writing A While Loop To Read Positive Integers From User Until User Enters EOF Character

Feb 24, 2014

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

[code]....

So I'm attempting to have this program take the users input of integers, pressing enter in between each one. If they enter a negative number it lets them know that its invalid. At the end of the program it takes all of the valid integers entered and must add them and average them. I've put the final println in there as a placeholder. If the user types in "6" then presses enter and types in "3" , the output is:

There were 3 valid numbers entered.
The sum of the valid numbers was --- and the average was ---.
There were 0 invalid numbers entered.

It then continues on allowing the user to enter more values. Here is the example output for correct code"

Enter a positive value (EOF to quit): 4
Enter a positive value (EOF to quit): 7
Enter a positive value (EOF to quit): 8
Enter a positive value (EOF to quit): 2
Enter a positive value (EOF to quit): -1
The number "-1" is invalid.

Enter a positive value (EOF to quit): 8
Enter a positive value (EOF to quit): 0
Enter a positive value (EOF to quit): -4
The number "-4" is invalid.

Enter a positive value (EOF to quit): CTRL-D

There were 6 valid numbers entered.
The sum of the valid numbers was 29 and the average was 4.83.
There were 2 invalid numbers.

View Replies View Related

Unable To Print A Loop Inside Array Of Greater Size Than Loop Itself

Jan 27, 2015

I am trying to print a loop inside an array of a greater size than the loop itself. Like for example I have an array of size 7 but it has only 3 elements.

int[] array=new int[7]
array[0]=2;
array[1]=3;
array[2]=4;

now what I want to do is print these three numbers in a loop so that my array[3]=2;array[4]=3;array[5]=4 ...... till the last one. Also the array could be any size and not just 7.

View Replies View Related

While Loop Inside A For Loop To Determine Proper Length Of Variable

Feb 25, 2014

Here's the code: it's while loop inside a for loop to determine the proper length of a variable:

for (int i = 0; i < num; i++) {
horse[i]=new thoroughbred();
boolean propernamelength = false;
while (propernamelength==false){
String name = entry.getUserInput("Enter the name of horse "

[code]....

I was just wondering what was going on here -- I've initialized the variable, so why do I get this message? (actually the carat was under the variable name inside the parentheses.

View Replies View Related

When Type Quit To Close Outer Loop / It Still Runs Inner Loop

Nov 2, 2014

I have everything else working. My problem is that when i type "quit" to close the outer loop. It still runs the inner loop. The National Bank manager wants you to code a program that reads each clients charges to their Credit Card account and outputs the average charge per client and the overall average for the total number of clients in the Bank.

Hint: The OUTER LOOP in your program should allow the user the name of the client and end the program when the name entered is QUIT.In addition to the outer loop, you need AN INNER LOOP that will allow the user to input the clients charge to his/her account by entering one charge at a time and end inputting the charges whenever she/he enters -1 for a value. This INNER LOOP will performed the Add for all the charges entered for a client and count the number of charges entered.

After INNER LOOP ends, the program calculates an average for this student. The average is calculated by dividing the Total into the number of charges entered. The program prints the average charge for that client, adds the Total to a GrandTotal, assigns zero to the Total and counter variables before it loops back to get the grade for another client.Use DecimalFormat or NumberFormat to format the numeric output to dollar amounts.

The output of the program should something like this:

John Smith average $850.00
Maria Gonzalez average $90.67
Terry Lucas average $959.00
Mickey Mouse course average $6,050.89
National Bank client average $1,987.67

Code:

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = "";
int charge = 0;
int count = -1;
int total = 1;
int grandtotal = 0;
int average = 0;
 
[code]....

View Replies View Related

Why Are There Five Integers Instead Of Only Two

Jan 22, 2015

After the code is executed the array is supposed to contain 2,3,5,3,2. However, prime[4-0]= prime[i] and prime[4-1]= prime[i]... doesn't the loop terminate before it iterates a third time? Why are there five integers instead of only two?

int[] primes= {2,3,5,7,11};
for (int i=0; i<2; i++)
{
primes[4-i]= primes[i];
}

View Replies View Related

First 2 Integers Of Second Array Are Always 0?

Jan 20, 2015

import java.util.Arrays;
import javax.swing.JOptionPane;
public class Student {
public static void main(String args[]) {
String [] A =new String [4]; //krijon tabelen e emrave

[Code] ....

It Prints [firstname,secondname,thirdname,fourthname]

and [0,0,7,9]

The problem is that the first 2 integers of the second array are always 0 even if i put another grade like for example 6 or 7...

Our teacher asked to input the names and grades of the students using JOptionPane and then find the MINIMUM grade and how many times this grade is repeated...

View Replies View Related

Sum Of Numbers Between Two Integers

Nov 19, 2014

I was trying to get sum of numbers between two given integer and managed to do it.

public int sum(int a, int b) {
int sum=0;
while(a <= b) {
sum+=a;
a++;
}
return sum;
}

in here; when I enter the values i.e 2 and 5, it calculates 2+3+4+5 and gives me the result 14.

my question is, how could I exclude a and b in this calculation ( in this case exclude 2 and 5 and return 3+4 )

Bonus question ; how could I only calculate the odd (or even) numbers between those integers?

View Replies View Related

Reading Only Integers Not Text?

Feb 19, 2014

my code is below and i want to read only integers.BUT the text file is starting with text and it stops executing without reading the numbers.Also i want to add the 3 parameters of each line.

try{
File fl = new File("C:/Users/Mario/Desktop/testing.txt");
//BufferedReader rd = new BufferedReader(new FileReader(fl));
Scanner sc = new Scanner(fl).useDelimiter("s+");
LinkedList<Integer> temps = new LinkedList<>();
sc.useDelimiter(System.getProperty("line.separator"));
  while(sc.hasNext()){

[code]...

View Replies View Related

Swing/AWT/SWT :: Using JComboBox With Integers

Mar 24, 2015

I am trying to set some serial port parameters here:

public synchronized void connect(String port, String rate, String data, String stop, String parity) throws Exception {

CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);

[Code].....

To set the serial port parameters i need to use Integers instead of strings.

So, how i turn my string EG:

String[] baudRates = { "2400", "4800", "9600", "14400", "19200", "38400", "56000", "115200" };

into Integers for my combo box

View Replies View Related

How To Get Highest Value Of Array Of Integers

Jul 1, 2014

I am trying to write a method that returns the busiest hour in a logAnalyzer class that read web server data and analyze hourly access patterns and stores them in an array. My problem is, in order to get the busiest hour, I need to go through the hourCounts array to find the element with the biggest count.

View Replies View Related

Method To Add And Multiply Integers

Mar 12, 2015

Develop a method that accepts as data input three integer numbers, calculates the sum and the product of the numbers, and displays the sum and product.

View Replies View Related

Find Number And Sum Of All Integers

Oct 29, 2014

Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7.

View Replies View Related

Array Of Integers - Cannot Be Converted To Int

Dec 18, 2014

I have a method that receives an array of integers and saves the ID of the user inside the array of integers and I keep getting the error: "int[] cannot be converted to int".Here is the code:

public boolean Borrow (String TitleOrAuthor,int id){
int count = 0;
int b1 = 0;
int BookCount [] = new int [b1];
for (int i=0;i<Bcount;i++){
if(Booklist[i].getTitle().equals(TitleOrAuthor))
for(int j=0;j<b1;j++){
BookCount [j]= Booklist[i].getCopies();
BookCount [j]= id;
b1++;

[code]...

View Replies View Related

Formatting Integers Into Money

Apr 15, 2014

Having the following fields for my money class.

import java.text.DecimalFormat;
public class Money {
//Fields for money will hold dollars and cents
private long dollars;
private long cents;

My task is to use those fields and make a toString method that returns them like a dollars sign. For instance, if there are 32 dollars and 40 cents, then in my String method I have to return something similar to this "$32.40."

I have already tried some of the methods, but they don't seem to work fine.

public String toString() {
DecimalFormat formatter=new DecimalFormat("$#0");
DecimalFormat formatCents=new DecimalFormat(".00");
return formatter.format(dollars)+ formatCents.format(cents);
}

Code:

import java.text.DecimalFormat;
public class Money
{
//Fields for money will hold dollars and cents
private long dollars;
private long cents;
 
[Code] ....

Actually changed a little on my code and I believe strongly this should work; however, doesn't seem to. In my demo,

public class Dem {
public static void main(String[] args) {
Money myMoney=new Money(7.10);
System.out.print(myMoney.toString());
}
 
}

I pass this, but I get "$700.00" as the answer... confused...

My calculation is wrong in the toString method, but still the cents do not appear to be showing.

View Replies View Related

How Can Two Same Integers Be Interpreted As Different Numbers

Sep 12, 2014

I have a code like following. x and y are both Integers and have same values (e.g. 5). But they are interpreted as different values. Then, it validates the following condition.

Java Code: if (x != y) {
"x and y are different..."
} mh_sh_highlight_all('java');

View Replies View Related

Calculate Sum Of All Integers Between 1 And Given Integer N

Aug 3, 2014

So I wrote a method that simply calculates the sum of all integers between 1 and a given integer n. The method works fine however, as n gets big the solution will have time and space problems. Some I'm just curious if there is a better method than my iterative one that would produce a better Big O value.

public static int sum(int n)
{
int total = 0;
for (int i = 1; i <=n; i++)
total += i;
return total;
}

View Replies View Related

Two Dimensional Array Of Integers

Nov 7, 2014

I am workinh with a couple of functions that deal with two dimensional (square) arrays of integers, doing things like checking equality, etc. For example, I know that I get an ArrayOutOfBoundsException in the isEqual function, but I don't know why.

public class MatrixUtils {
//This function checks if two matrices are equal
public static boolean isEqual(int A[][], int B[][]) {
for(int i=0; i<A.length; i++) {
for(int j=0; j<A.length; i++) {
if (A[i][j] != B[i][j]) return false;

[Code] ....

View Replies View Related

How To Take User Input As Integers

Jun 2, 2009

Suppose I write a program to multiply two numbers.

The user enters the numbers as follows:

2
3

How do I extract these integers inside main? [Explain the case where the integers are on two separate lines].

What to do for the newline inbetween?

View Replies View Related

Adding Integers From File But Not Letters

Dec 4, 2014

I have devised a simple program that reads a file and then adds up al the integers in the file and print the result, for example if the file had the numbers
1 2 3 4 5 6 7 8 9 10
then the program would print 55

However i have trouble when non integers are put into the file for example if it was
1 2 3 string 4 5 6 test 7 8 9 10

then i get:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Week7.Task3.filereader(Task3.java:25)
at Week7.Task3.main(Task3.java:14)

my code is as follows

package testing;
 
import java.util.*;
import java.io.File;
import java.io.IOException;
public class summingInts {
public static void main(String[] args)
throws IOException {
Scanner textfile = new Scanner(new File("intSum.txt"));

[code]....

View Replies View Related

How To Change Zeros To Integers In Do-While Statement

Mar 31, 2014

How do i change the outcome to below? at the moment it is all 0? How I can clear some clouds in this area.

Competitor 1: 11111
===============================================

Competitor 2: 22222
===============================================

Competitor 3: 33333
===============================================

Competitor 4: 44444
===============================================

Competitor 5: 55555
===============================================

Here's the code:

case 2: System.out.println("Menu item 2");
for(int i=1; i<MAX_COMPS;i++){
System.out.print("Competitor " + i + ": ");
for (int j=1;j<MAX_SCORES;j++)
System.out.print(scores[i][j] + " ");
System.out.println("");
}

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved