The code works. But, I need to include long integers. How can I do that? I've tried a million things. I'm not good at this either so it takes me 5 times longer to get a simple code. Please help.
import java.util.Scanner;
public class Exercise2_6M
{
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();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Read the input value as a string and then use the BigInteger class to perform calculations with very large values.
A recursive solution can be much leaner:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter an long:");
long lng = input.nextLong ();
int sum = getDigitSum (lng);
System.out.println ("Sum all digits in " + lng + " is " + sum);
}
public static int getDigitSum (long num)
{
if (num < 10L) return (int) num;
else return ((int)(num % 10)) + getDigitSum (num/10L);
}
}
Related
I am trying to follow these instructions:
Write a program that will ask the user for the value of an integer n, and compute the sum 1 + 2 + 3 + 4 + ... + n. The requirement for this lab is that you write a recursive function that returns the result of the sum (integer) and takes one argument, n, of type integer. You will then call the function and print out its results as follows:
int mysum = recursive_addition(n);
System.out.println("The sum 1+2+...+n is: "+ mysum);
the problem is on line 20 because of the error below
Main.java:20: error: method main (String[]) Is already defined in class Main
private static void main (String args[])
^
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Please enter a integer: ");
int n = s.nextInt();
int mysum = recurSum(n);
System.out.println("The sum 1+2+3+4 is :" + n );
}
public static int recurSum(int n)
{
if (n <= 0)
return n;
return n + recurSum(n - 1);
}
public static void main (String args[])
{
int n = 5;
System.out.println(recurSum(n));
}
}
As the compiler stated, you are duplicating the main entry points of your application.
Just remove the last main function and modify as follow
Here is the working code
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Please enter a integer: ");
int n = 5; // Just put there the number
int mysum = recurSum(n);
System.out.println("The sum 1+2+3+4 is :" + n );
}
public static int recurSum(int n)
{
if (n <= 0)
return n;
return n + recurSum(n - 1);
}
}
I'm trying to make this program that will print out numbers in ascending order between two input numbers. I made it work as a method and I can call the method in Main, but what I really want to do is to input the two numbers in Main and not in the method.
So something like this:
System.out.println(”Two numbers in ascending order”);
(input two numbers in console)
And then after this, call the method that will print in ascending order between the chosen numbers of Main.
I’m new to this and i’ve tried several things, but I can’t seem to figure out what to do. Would appreciate som help.
This is how the code looks now.
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
// calling method
int ascending1 = ascending();
}
public static int ascending() {
int min;
int max;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
min = sc.nextInt();
max = sc.nextInt();
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
Pass in the two inputs as parameters to your method, something like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
System.out.println(ascending1);
}
And now :
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
Notice that now the definition of ascending() takes in two parameters of type int. The values are passed from the main method to the method.
You can input the numbers in the main method and then pass them to another method:
public class AscendingOrder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
}
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can read the command line arguments or place the scanner in main function and pass the arguments
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
System.out.println("Entered first number is: "+args[0]);
System.out.println("Entered Secomd number is: "+args[1]);
int ascending1 = ascending(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static int ascending(int min,int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can get the numbers in main method and sort them in the main method itself. Java 8 makes it so easy with streams.
public static void main( String[] args ) throws Exception {
Framework.startup( );
Scanner sc = new Scanner( System.in );
System.out.println( "Two numbers in ascending order" );
int num1= sc.nextInt( );
int num2= sc.nextInt( );
Arrays.asList( num1, num2).stream( ).sorted( ).forEach( System.out::println );
}
I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
You have not get an input from user and also you do nothing to make average.
Try this code, and if you have other requirements, update the question.
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
output sample:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.
import java.util.*;
public class Table {
This part is used to read ANY user input Strings included.
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
Here we build our "bar graph":
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
Here we calculate the sum:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
Here we get our average:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
Here the integer digits are extracted!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
Our example output for: asdf45313ha is:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3
My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}
I am writing a program that should output the factorial of any number which is inputted by the user. The program correctly gives an output from 0 to 12 but if I enter 13, the output is 1932053504 but in my calculator, 13! = 6227020800.
Also in 32! and 33!, the output is negative (32! = -2147483648). Starting 34!, the output is zero(0).
How can I fix this? I want the program to provide the correct output of any number entered by the user.
import java.util.Scanner;
import java.io.*;
public class one {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int val = in.nextInt();
int factorial = 1;
for (int i = 1; i <= val; i++) {
factorial *= i;
}
System.out.println("The factorial of " + val + " is " + factorial);
}
}
It exceeds the max value an integer can take
Max integer value:2147483647
Max long value: 9223372036854775807
Max double value: 7976931348623157^308
Use long, double or BigInteger, which doesn't have upper boundaries
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int val = in.nextInt();
int factorial = 1;
int i = 1;
while (i <= val) {
factorial = factorial * i;
i++;
}
System.out.println("The factorial of " + val + " is " + factorial);
}
}
That's how you'd do it with a while loop instead