Program That Accept Input Of Positive Integer And Sum All Digits

Jan 28, 2015

I am attempting to write a program that accepts input of a positive integer, reports each digit and then the sum of all digits. This is what I have so far:

*/
 package numbersum;
import java.util.*; 
public class Week4NumberSum {
static Scanner console = new Scanner(System.in); 
/**
* @param args the command line arguments

[Code]...

It works if I enter 1234567891 (10 digits)
Enter a positive integer: 1234567891
digit: 1
digit: 2
digit: 3
digit: 4
digit: 5
digit: 6
digit: 7
digit: 8
digit: 9
digit: 1

The sum of the digits is 46

But if I enter 11 digits, it fails:

Enter a positive integer: 123456789123 (12)
Exception in thread "main" java.util.InputMismatchException: For input string: "123456789123"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at week4numbersum.Week4NumberSum.main(Week4NumberSum. java:26)

java - Scanner error with nextInt() - Stack Overflow gives me some infor for InputMismatchException - which I find described as In order to deal with this exception you must verify that the input data of your application meet its specification. When this error is thrown, the format of the input data is incorrect and thus, you must fix it, in order for your application to proceed its execution.

I don't understand why the 10 digit integer is OK but the 11 or > digit integer is a mismatch.

View Replies


ADVERTISEMENT

Write A Java Program That Reads A Positive / Non-zero Integer As Input

Aug 1, 2011

Write a Java program that reads a positive, non-zero integer as input and checks if the integer is deficient, perfect, or abundant.

A positive, non-zero integer, N, is said to be perfect if the sum of its positive proper divisors (i.e., the positive integers, other than N itself, that divide N exactly) is equal to the number itself. If this sum is less than N, the number is said to be deficient. If the sum is greater than N, the number is said to be abundant.For example, the number 6 is perfect, since 6 = 1 + 2 + 3, the number 8 is deficient, since 8 > 1 + 2 + 4, while the number 12 is abundant, since 12 < 1 + 2 + 3 + 4 + 6.

SAMPLE OUTPUT:

1.)Input N: 5

5 is deficient.

2.)Input N: 6

6 is perfect.

3.)Input N: 18

18 is abundant.

View Replies View Related

User To Input Integer And Then Outputs Both Individual Digits Of Number And Sum Of Digits

Feb 2, 2015

Goal is to: Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits.

First I don't know where I made mistakes here, and the only error it finds right now is that str2 was not initialized and I cannot figure out where/when to initialize it.

import javax.swing.JOptionPane;
public class DigitsAndSum {
public static void main (String[] args) {
String str1;
String str2;
int int1 = 0;
int int2 = 0;

[Code] ....

View Replies View Related

JTextField That Accept Only Integer Input?

Jul 5, 2014

I have a GUI with a JTextField. I need to check that the input entered by the user is made up of only integers.

For example I accept: 1, 10, 530, ...

I do not accept: -10, 1.5, -6 ...

I would like to implement this control by using a regular expression so I would have a code like that.

JTextField text = new JTextField();
String input = text.getText();
boolean bool = checkInteger(input);
if(bool)
System.out.println("Ok");
else
System.out.println("Error");

The checkInteger(String input) method should check if the input string is correct or not.

How can I do to implement this control with regular expressions?

Is there an easier way to do it?

View Replies View Related

Accept Integer As Input - Display Even Or Odd

Apr 14, 2014

This program is supposed to accept an integer as an input and display the message that the number is even or odd. The main method calls a Boolean method. Write a method private static boolean iseven(int number and the message is printed from the Main method. This is what I have.

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

[Code] ....

I know the message is not being printed from the Main method. I'm not sure how to do that.

View Replies View Related

Input Validation - Where Condition Is A Word From Set And Value Is A Positive Integer

Mar 18, 2015

I am trying to create a program that first asks the user for an input in the form: condition = value, where condition is a word from the set {limit, deficient, abundant, perfect, prime}, and value is a positive integer. Then it verifies the input. If the input is invalid it prints a message indicating that and terminates. If the input is valid it prints a table with the number of abundant, deficient, perfect and prime numbers less than or equal to N, where N = 1, 2, 3, ..., limit.

My problem is with the input validation. i want it to read the value as a string and verify if it's integer.

Here is my code

import java.util.Scanner;
 public class Factors
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int n, f, fsum, p=0, a=0, d=0,pe=0,limit=0,abundant=0, deficient=0;
System.out.print("Enter stoping condition (condition = value): ");
String cond = scan.next();

[Code] ....

View Replies View Related

Read From User Input (integer) And Reduce It By Multiplying Its Non-zero Digits

Nov 15, 2014

Write a program that reads from the user an integer and reduce it by multiplying its non-zero digits. The result of the multiplication is a number which is to be reduced as the initial one. This process continues until an integer of one single digit is obtained. For example:

64734502 (6 * 4 * 7 * 3 * 4 * 5 * 2) 20160 (2 * 1 * 6) 12 (1 * 2) 2

Your program should display the number obtained in every iteration.

Sample run1
Enter an integer: 64734502
After iteration 1: 20160
After iteration 2: 12
After iteration 3: 2

Sample run2
Enter an integer: 97737999
After iteration 1: 6751269
After iteration 2: 22680
After iteration 3: 192
After iteration 4: 18
After iteration 5: 8

View Replies View Related

Prompt User To Input Integer And Then Output Both Digits Of Number And Their Sum

Jun 7, 2015

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. 
 
Now I have a code for spacing out the integers, and I have a separate code for adding the digits. But I am not sure how to merge them together. Both of them work independently
 
Spacing code:
import java.util.*;
public class SumoftheIntegers
{
static Scanner console=new Scanner(System.in);
public static void main(String []args) {
int num1, test, rem;
int counter = 0;

[Code]...

Now the sum of the integers code:
 
import java.util.Scanner;
public class sum
{
    public static void main(String[] args)
    {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
// Enter amount
        System.out.print("Enter an integer: ");
        int integer = input.nextInt();

[Code]...

View Replies View Related

Program To Accept String Float And Integer As Command Line Arguments

Feb 8, 2015

Write a java program to accept a string, float and an integer as command line arguments. String value should be displayed. Also the program should display the maximum value of two numbers. Use Integer.parseInt() and Float.parseFloat()

View Replies View Related

Program Will Only Accept Input From 1 String?

Jan 14, 2015

I am trying to create a fortune teller and everything is running fine except the program does not prompt you to answer the questions

Do you like donuts?
and
What did you have for breakfast?

Here is the code this is in Bluej :

import java.util.Scanner;
public class FortuneTeller {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to Fortune Teller");

[Code] .....

View Replies View Related

Calculate The Factors Of A Positive Integer Number

Mar 16, 2014

lines 7, 8, &12 "primes" are underline in red (prime cannot be resolved) is what pops up when i hover over the x's.

i don't get why that is.

package assignment7;
public class Exercise3
{
public static void main(String[] args)
{
Prime.setSize(1000);
for (int p = Primes.next(); p < 30; p = Primes.next())

[Code]...

View Replies View Related

Calculate Factors Of Positive Integer Number

Mar 17, 2014

Lines 7, 8, &12 "primes" are underline in red (prime cannot be resolved) is what pops up when i hover over the x's.

I don't get why that is.

Java Code :

public class Exercise3
{
public static void main(String[] args) {
Prime.setSize(1000);
for (int p = Primes.next(); p < 30; p = Primes.next()) {
int n = (int)Math.round(Math.pow(2,p)) - 1;
System.out.printf("%d 2^%d-1%d", p, p, n);
if (Primes.isPrime(n))

[Code] ....

View Replies View Related

Read Positive Integer N And Plot 3 Triangles Of Size N

Oct 10, 2014

Write a Java program that reads positive integer n, 1 ≤ n ≤ 13, and plots 3 triangles of size n as shown below.

For n = 4, for instance, the program should plot: (works for n = 5 and n = 6 etc.)

triangle 1

1
2 3
4 5 6
7 8 9 10

triangle 2

_ _ _ 1
_ _ 3 2
_ 6 5 4
10 9 8 7

triangle 3

_ _ _ 1
_ _ 3 3 3
_ 5 5 5 5 5
7 7 7 7 7 7 7

import java.util.Scanner;
class Loops { 
void plotTriangle1(int n) {
int t = 1;
for (int i = 1; i <= n; i++) {
System.out.println(" ");
for (int j = 1; j <= i; j++) {
System.out.printf("%3d", t++);

[Code] ....

Currently compiles to this: Enter n(1-13):4
1
2 3
4 5 6
7 8 9 10

Format of the triangles, I couldn't get the spacing to work so I used underscores to replicate the blank space....

View Replies View Related

Digit Sum Of Integer Is Sum Of All Digits

Oct 13, 2014

Digit sum of an integer is the sum of all its digits. For example, the digit sum of 123 is 1+2+3 = 6

and the digit sum of 99 is 9 + 9 = 18.

But how to write the programm that will count those numbers?

View Replies View Related

Breaking Integer Into Individual Digits?

Oct 12, 2003

I'm trying to figure out how to read in an integer and break it down into a sequence of individual digits in reverse order. Example: an integer input of 12345 gives an output of54321.

View Replies View Related

Nesting Loops - Odd / Even And Zero Digits In Integer Value

Oct 13, 2014

So I am trying to do this program but I can't figure out how to nest it properly. The prompt is :

Design and Implement an application that determines and prints the number of odd,even,and zero digits in an integer value read from the keyboard.

The catch is, strings are not allowed. This is what I have so far :

import java.util.Scanner;
 public class OddEvenZero {
 public static void main(String[] args) {
int zero = 0, even = 0, odd = 0, num, num2;

[Code] ....

View Replies View Related

Accept Array Of Non-negative Integers And Return Second Largest Integer

May 22, 2015

Write a function that accepts an array of non-negative integers and returns the second largest integer in the array.

Return -1 if there is no second largest.

The signature of the function is int f(int[ ] a)

Examples:

if the input array isreturn{1, 2, 3, 4}3{{4, 1, 2, 3}}3{1, 1, 2, 2}1{1, 1}-1{1}-1{}-1 

In the signature what I understood is, I should write my function with the given signature,

The return type is "int"

method name is "f"

parameter is "a" right ?
 
Writing my doubts beside the particular line in the code

public static void main()  // In the answer why they didn't use the class ?

In main method why they didn't use parameters ?(String[] args)

{
a1(new int[]{1, 2, 3, 4}); // what is "a1" here is it array name ? this line initializing the array ?
a1(new int[]{4, 1, 2, 3});
a1(new int[]{1, 1, 2, 2});
a1(new int[]{1, 1});
a1(new int[]{1});
a1(new int[]{});


static int a1(int[] a) // what is "a" here parameter ? and "a1" is method name ? why they used the array name and method name same ?

{
int max1 = -1;
int max2 = -1;
for (int i=0; i<a.length; i++)

[Code] .....

View Replies View Related

Simple Recursion Method - Accept Integer Parameter N And Return Sum Of First N Reciprocals

Nov 1, 2014

I am practicing some basic recursion and I was trying to solve this problem

Write a method sumTo that accepts an integer parameter n and returns the sum of the first n reciprocals. In other words:

sumTo(n) returns: 1 + 1/2 + 1/3 + 1/4 + ... + 1/n

For example, the call of sumTo(2) should return 1.5. The method should return 0.0 if passed the value 0 and should throw an IllegalArgumentException if passed a value less than 0.

This is my attempt to do it , however my output is always a 0.0 , and i do not understand why :

public static double sumTo(int n ){
if(n<0){
throw new IllegalArgumentException();
}
else if (n==0){
return 0.0;

[Code] .....

View Replies View Related

Accept List Of Integers As Parameter And Return Number Of Times Most Frequently Occurring Integer

Nov 20, 2014

Write a method maxOccurrences that accepts a list of integers as a parameter and returns the number of times the most frequently occurring integer (the “mode”) occurs in the list. Solve this problem using a map as auxiliary storage.

If the list is empty, return 0.

View Replies View Related

Sum Of Odd Digits Of Input

Oct 14, 2014

I have it so it gives me the sum of any digit, i just cant figure out how to get only the odd digits to add up. for example if I were to type 123. The odd numbers = 4 but using this program i get 6

class SumOfDigits {
public static void main(String args[]) {
int sum = 0;
System.out.println("Enter multi digit number:");

[Code] ....

View Replies View Related

How To Accept Enter As Empty Input

Nov 8, 2014

How can I get enter(return) as empty input from user?!

scanner.next will wait until I input a string ...

But I want it when I hit return sets the variable to empty string ...

View Replies View Related

Accept User Input And Then Print Its Average In A Serial Way

Mar 13, 2015

I want to write a program that accepts user input and then prints its average in a serial way.

Suppose i enter 5. I should get result 5 first time then i input 10 then it should return the average of (5 and 10) and then i enter say 20 it should return average of (5,10 and 20) and so on.

View Replies View Related

Multiplying Last 2 Digits In A Year From User Input

May 2, 2014

I Have been playing with this for while, and I can not seem to get my head around, how I can do this. I need to get the last two digits of a year that a user will enter. For example, a date like July 2 , 2014, I want to get the last two digits of year 2014 which are "14" and divide it by 4. This will give me 3.5; how ever I will disregard the ".5" and just keep the 14. I have no problem doing the division, my biggest this is how to just get the last two digits of a year. This is what I have so far, it is basically a template of how I want my program; I just need getting the last 2 digits of a year.

public class DateCalc
{
public static void main (String[] args)
{
String month;
int day;
int year;

[Code] ....

" This will give me 3.5; how ever I will disregard the ".5" and just keep the 14 ". I meant that I just want to keep the 3 from the 3.5 that will be generated when you divide 14 by 4.

View Replies View Related

Take User Input And Display Sum Of Digits Of Entered Number

Nov 6, 2014

I have returned with yet another problem but I think this one might be a bit easier to fix.

So the whole MO of this program is to take user input, and display the sum of the digits of the number they entered. I am supposed to do this by utilizing methods. So far this is what I have and when I compile it tells me that it "cannot find symbol", which I don't understand as I define what "m" is in the for loop. The other error is that it says:

"Exercise6_2.java:22: error: incompatible types: possible lossy conversion from long to int
return result;
^

I don't understand why it's giving me this error nor do I understand why result seems to inherently be an int. (Also the public static int sumDigits(long n) method was given to me by the book so that is what I am supposed to use).

import java.util.Scanner;
public class Exercise6_2 {
public static void main(String[] args) { 
Scanner input = new Scanner(System.in);
System.out.println("Enter a integer");
long n = input.nextLong();

[Code]...

View Replies View Related

Write A Program For Converting Positive Binary Inputs Into Hex

Sep 29, 2014

I am trying to write a program for converting positive binary inputs into hex.Why am i getting this errors while compiling my binary to hex converter..

Exception in thread "main" java.lang.NumberFormatException: For input string: "148.0"
at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at BinToHex.convertbintohex(BinToHex.java:24)
at Test.main(Test.java:4)

Here is my BinToHex class

import java.io.*;
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="1001.01";
String hexOutput,intpart,tempDecString,hex = null;

[code]....

View Replies View Related

Program Won't Accept Command Lines?

Oct 24, 2014

A friend and I are working on a project in which we must test "super anagrams" (anagrams in which all characters in the first string are found in the second). We have a driver and definitions class pasted below:

Definition
class SuperAnagram{
String left = new String("");
String right = new String("");

[code]....

In the driver class, we get "cannot find symbol" errors at the beginning of cleanStrings and isSuper, both inside and outside of the if statement.

View Replies View Related







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