Method To Add And Multiply Integers
Mar 12, 2015Develop 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 RepliesDevelop 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 RepliesI am trying to create a method that takes an array of integers and prints it out using System.out.print. I'm having trouble creating the right way to print it out since I cannot find a way to convert the int array to a string to print it out.
public static String printArray(int[] num){
for (int i=0; i<num.length;i++){
String msg = num[i];
}
return System.out.print(msg + " ");
}
I'm making a method to take an array of integers and rearrange the numbers from least to greatest, using for loops.
I'm getting the error "java. lang. ArrayIndexOutOfBoundsException: 8,
Portion of the ArrayMethods class with the sorting method
Java Code:
public static Integer[] sortArray (Integer[] a)
{
int swap;
for (int i = 0; i < a.length; i++)
[code]....
How do I code this without having the need to use iterator? Code a Java method that accepts an ArrayList of integers and an integer. The method should delete all elements in the array list exactly divisible by the integer and return the number of remaining elements.
View Replies View RelatedI would like to multiply the amount stated inside program by user input. I currently have
public static void setTicket(double ticket)
{
//if statement for tickets
if (ticket == 1)
Ticket = 10.00;
else if (ticket == 2)
Ticket = 20.00;
else if ( ticket == 3)
Ticket = 30.00;
The user should enter 2 and the value should show 20.00. This does work however im looking for a way to say enter 2 = 2*10 instead of stating each value individually.
My assignment is to write some code that will multiply every number in an array by 2 and print it out. This is using a site zyante which is a interactive online book kind of thing.
I have tried For (i=0; I < 8; i++) with like userVals = userVals * 2) }
And it doesn't like that so i'm guessing i am no where close to right. The chapter doesn't give me any example of doing anything close to this so i am completely lost on what i have to do.
This is the program :
import java.util.Scanner;
public class NegativeToZero {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 8; // Number of elements
[Code] .....
public static void main (String [] args) {
int a = (int) 0.25;
int b = (int) 1.25;
int result = a + b;
System.out.println("Result of addition is "+ result);
}
}
I am trying to make a program to multiplies two numbers without using the "*" operator. My idea was to add x number y amount of times, which is the same as multiplication. I did this with a for loop, but zero is always returned as the answer. How can I fix this?
public class secondMult {
public static void main(String[] args){
System.out.println(multWithSum(4,5));
}
public static int multWithSum(int x, int y){
int sum = 0;
for(int i = 0; i==y;i++){
sum = sum + x;
}
return sum;
}
}
I was suppose to create a simple Java program for calculating the area of a rectangle (height * width). Then check the user’s input, and make sure that they enter in a positive integer, and letting them try again if they enter in a negative number. (I'm not sure how to get them to try again.
I am suppose to use an "if" statements and indeterminate loops to achieve the solution. The program will have the following requirements:
1. Ask the user to enter in both a height and width (as an integer)
2. If the user enters in a negative number, display an error
3. If the user enters in a negative number, give them another chance to enter in the correct value
4. Calculate the area and display to the screen once two positive integers have been entered.
import java.util.Scanner;
public class RectangleAreaCalc
{
public static void main(String[] args)
{
int length;
int width;
int area;
[Code] ....
I have a program where the user enters in the miles and then it is supposed to get multiplied by feet but I keep getting this error.
GetUserInfo.java:12: error: bad operand types for binary operator '*'
int total = name * feet;
^
first type: String
second type: int
1 error
This is my code so far :
import java.util.Scanner;
public class GetUserInfo
{
public static void main(String[] args) {
String name;
int miles;
[Code] ....
So I need to generate 10 random integers in the range 1-20 but i have to store them in an array called numbers. Then I have to call a method called displayArray which displays the contents of the array and for the assignment i have to use a for loop to traverse the array. The method header for the displayArray method is:
public static void displayArray(int[] array)
This is what I have done
public class RandomIntegers {
static int numbers = 0;
public static void displayArray(int[] array) {
System.out.println(numbers + "Numbers Generated");
[Code] .....
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];
}
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...
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);
}
}
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?
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++);
}
}
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] ....
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]...
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
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 RelatedMy 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.
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 RelatedI 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]...
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.
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');
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;
}