Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a code that will get the sum of all the digits of the input,
sample input: 241 sample output: 7
But there are restrictions in in making the program, only the basic operations, functions should be used and no string function is to be used in getting the said sum of the digits only (loop, /, %, *,-,+)are allowed to be used.
The program I am thinking should start with this..
public class SumOfDigits{
public static void main(String args[]) throws Exception{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
while(){
}
}
}
One option would be to use a modulus trick to isolate, and then sum, each digit in the input number:
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
Follow the link below for a working demo.
Demo
modulu 10 of the number will give you the last digit, the dividing it by 10 will give you the other digits, due to integer division. You can loop until you've handled all the digits:
int sum = 0;
while (num != 0) {
sum += (num % 10);
num /= 10;
}
you can use a recursive function like this
import java.util.Scanner;
public class Main {
Scanner scanner ;
int result = 0;
public static void main(String[] args) {
// initialize new instance of current class
Main thisIns = new Main();
// initialize scanner instance for this instance
thisIns.scanner = new Scanner(System.in);
//calling for getting user inputs
int i = thisIns.getUserInput();
//get the sum of the integer
thisIns.getSumOfInterger(i, 0);
System.out.println("result is " + thisIns.result);
}
public int getUserInput(){
System.out.println("Please enter an integer : ");
int i = scanner.nextInt();
return i;
}
public void getSumOfInterger(int i, int moduler) {
if (i != 0) {
moduler += i%10;
getSumOfInterger(i/10, moduler);
// return 0;
}else{
result = moduler;
}
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to count a range of number with a for loop using input from scanner.
Tried writing the code but still no results
package com.example.myapplication;
import java.util.Scanner;
public class dsd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int firstnum = sc.nextInt();
System.out.println("Enter first number:");
int secondnum = sc.nextInt();
System.out.print("counting ");
for (int i = firstnum; i >= secondnum; i++) ;
{
System.out.print(i);
}
}
Upper limit :5
Lower Limit :2
Expected to see COunting 2 ,3 ,4, 5
I think it would be better to use a camel case to match the coding convention. And if you put a semicolon after the for loop, the following code will not be executed. Of course, the conditional statements in the for loop seem a little wrong.
For the example given in the question, see the code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Upper limit:");
int firstNum = sc.nextInt();
System.out.print("Lower Limit:");
int secondNum = sc.nextInt();
System.out.print("counting ");
for (int i = secondNum; i <= firstNum; i++) {
System.out.print(i);
}
}
Result (in the terminal)
Upper limit:5
Lower Limit:2
counting 2345
I have seen this mistake many times:
for (int i = firstnum; i >= secondnum; i++) ;
Please remove the ;
Is the first number always greater than the second?
If so, you should write it as the code below.
// Delete semicolon. and less then change
for (int i = firstnum; i <= secondnum; i++) {
System.out.print(i);
}
In your code you have used the "sc" scanner for both firstnum/secondnum variable. The loop of your code will print only the last number inserted.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
int start, end;
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
/*
* The block try-catch highlights the fact that you cannot insert min
* number bigger than the max number
*/
try {
System.out.print("Enter first number:");
start = sc.nextInt();
System.out.print("\nEnter second number: ");
end = sc1.nextInt();
if(start > end) throw new Exception();
i = start;
while (i<=end){
System.out.println("count: " + i);
i++;
}
}catch(Exception e){
System.out.println("You cannot start with number bigger than 'end-number' ");
}
}
}
I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to write a portion of a program that calculates factorials using loops. I don't have any error messages, but I'm not getting any output.
Are there suggestions for my approach or is there a better approach using loops? Thanks!
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
while (number >= 1);
}
while (number <= 0);{
System.out.println("That's not a positive integer!");
}
System.out.print(factTotal);
}
}
This is the way I would approach the factorial portion of your problem. I would do away with the do/while loops because it appears that you are getting stuck in an infinite loop if you aren't getting output.
//Call this method when you want to calculate the factorial
public int factorial(int num){
for(int i = num-1; i > 1; i--){
num *= i;
}
return num;
}
This is what it would look like in your code.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
if(number > 0){
factTotal = factorial(number);
System.out.print(factTotal);
}
else
System.out.println("This is a negative number");
}
#Pernicious, Please see your program with slight modifications and my comments added. I think this is what you were trying to do.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
// The input number check should be before factorial calculation
if(number <= 0){
System.out.println("That's not a positive integer!");
System.exit(0);
}
//Execute factorial
do {
factTotal = factTotal * number;
number--;
// while (number >= 1); This while should be after do{}, not within do{}
} while (number >= 1);
// This check should be done immeduately after user input, not after calculation of factorial.
// while (number <= 0);
// {
// System.out.println("That's not a positive integer!");
// }
System.out.println(factTotal);
}
}
In your code, in the do...while loop, you have used this while statement:
while (number >= 1);
Did you not notice the semicolon? And what is the point of this loop? Currently it is leading to an infinite loop as the value of number never changes and thus you are getting no output. Also, your second while loop should much rather be an if statement as shown below
That piece of code is equivalent to:
while (number >= 1)
{
//doNothing
}
I believe you meant to do:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
}
while (number <= 1);
if(number < 0)
{
System.out.println("That is not a positive integer");
}
else
System.out.print(factTotal);
}
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}
Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}
Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}