i cant get the code right to ask for a number like 12 and then say the sum of the number is 3 in java netbeans
i got this so far
public class Exercise2_6 {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner( System.in );
System.out.println("Enter a number between 0 and 1000");
// Enter a number between 0 and 1000
Scanner input = new Scanner( System.in );
int x = in.nextInt( );
System.out.println(" The sum of the digits is "n" ");
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
}
}
and it gives me back
run:
Enter a number between 0 and 1000
12
The sum of the digits is
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement
at Exercise2_6.main(Exercise2_6.java:55)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
Strings must be concatenated using the + operator.
Therefore, your statement of "n" = .... is not correct.
Replace
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
with
System.out.println("n = " + in.nextInt()/100);
System.out.println("n = " + in.nextInt()%100);
However, the above statements will refer to TWO different ints, one for each time nextInt() is called. I don't know the purpose of your code but you should get into the practice of storing variables incase you need to use them again.
If you stored each int locally, for example
int n = in.nextInt();
you could then refer to it again later, for example by appending the above statements to
System.out.println("n = " + n/100); ....
This will probably not be the most efficient or 'correct' way of doing it, but I'm a complete noob myself. So, this is how I managed it. By using a while loop.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int i, a = 0, x = 0;
System.out.println("Enter a number between 0 and 1000: ");
i = input.nextInt();
while(i != 0) {
a = i % 10;
i = i / 10;
x = x + a;
}
System.out.println("The sum of the digits in your number is: " + x);
}
}
Related
I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.
I need to create a program that asks for numbers until the user inserts a zero and after that it should print an average of the inserted numbers. But I'm only able to get average of the first input but not the latter ones.
public static void main(String[] args) {
double a = 0;
int b = 0;
Scanner input = new Scanner(System.in);
do {
b++;
System.out.println("insert a number");
a += input.nextDouble();
}
while (a > 0 );{
}
System.out.println("the average is " + a / b );
}
}
You don't have an input in your while check. you need to have another variable called, saying userInput:
userInput = input.nextDouble();
a += userInput;
}
while(userInput > 0)
....
You are adding values from input directly to a:
a+=input.nextDouble();
So, if you add values to a directly, you can't tell when user typed in 0 and the loop will be terminated only if a drops below 0, f.e when user input is 2, 3, -5
I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");
Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable
The directions are the following: read in the starting and ending integer number , display all numbers (inclusive) divisible by both 5 and 6 print 10 per line. The tenth number should be the number then a new line. Don't prompt to read in the starting and ending integer number.
Always output a new line after printing out all the numbers.
When I submit the assignment, it doesn't meet all the requirements. What am I doing wrong?
import java.util.Scanner;
public class Exercise4_10M {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = 1 ;
int k = input.nextInt();
for (int i = 1; i <= k; i++) {
if (i%5==0&&i%6==0)
System.out.print((count++ % 10 != 0) ? i + " ": i + "\n" );
}
System.out.println("");
}
}
read in the starting and ending integer number
You only read one number (and using as the ending integer number)
Don't prompt to read in the starting and ending integer number.
From my understanding you need to pass the numbers as arguments to the application, i.e. like this:
java Exercise4_10M 100 300
Those would then be written to the args parameter of main(...), i.e. it would look like this:
args = {"100","300"}
That would require you to check the number of parameters, parse them into integers and possibly account for switched parameters (i.e. what if they were 300 100?).
As a sidenote: System.out.println(""); - if you just want to write a newline, the "" parameter isn't needed.