Trouble printing an int value user entered - java

So I'm building a program that reads user input in integers and adds the value of all the integers togther
My main method is :
public static void main(String[] args) {
My current code is :
Scanner scanner = new Scanner(System.in); // imports scanner
System.out.print("Enter an number: "); // ask user to enter number
// Repeat until next item is an integer
while (!scanner.hasNextInt())
{
scanner.next(); // Read and discard offending non-int input or int + not int input
System.out.print("Please enter digits only: "); // tells user to enter again
}
// if user enters int , exits while loop
//adds ints entered
int userNumber = scanner.nextInt(); // Gets the int
int sumofUsernumber = (0);
while (userNumber > 0) {
sumofUsernumber = sumofUsernumber + userNumber % 10;
userNumber = userNumber / 10;
}
System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber)
In the last line it supposed to print ther number the user enetered then the sum of the number, instead it prints, 0.
For example : if user enters 101 I'm trying to get it to print
"The combined value of 101 is 2"
Instead it prints
"The combined value of 0 is 2"

You need to store userNumber in some other variable as you are mutating the input from user directly.
The following code will help you
// adds ints entered
int userNumber = 101;
int temp = userNumber;
int sumofUsernumber = 0;
while (temp > 0) {
sumofUsernumber = sumofUsernumber + temp % 10;
temp = temp / 10;
}
System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber);

Related

Proper placing of the myScanner.next() method using Scanner class

Question 2:
As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int counter = 0;
int addSum = 0;
while (counter < 3) {
counter++;
int numberEntered = 0;
System.out.println("Enter number " + counter + " :");
boolean hasNextInt = myScanner.hasNextInt();
if (hasNextInt) {
numberEntered = myScanner.nextInt();
// myScanner.nextLine(); //why can't myScanner.nextLine()
// could go here right after the number entered
// is captured and stored in the numberEntered variable;
addSum = addSum + numberEntered;
} else {
System.out.println("Invalid number entered");
}
// myScanner.nextLine only works if placed here before
// closing of the while loop;
myScanner.nextLine();
}
System.out.println("The sum of the numbers entered are " + addSum);
myScanner.close();
}
}
Right now, you are always incrementing the counter no matter what:
while (counter < 3) {
counter++;
Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.
You should only increment the counter when the user enters a valid number:
if (hasNextInt) {
counter++;
numberEntered = myScanner.nextInt();
Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:
System.out.println("Enter number " + (counter + 1) + " :");

Reverse integer including 0's in java

I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}

if/else statement is not being read correctly by the program

This is a program that list several facts about an integer input from a Scanner object. However, I'm having some trouble with the if/else statement at the end.
The problem is if the input is a positive integer other than 0, the program always reads this statement: System.out.println("j) It is smaller than its reverse value: " + reverse);. If it's a negative int, it always prints System.out.println("j) It is bigger than its reverse value: " + reverse);.
I think it's because the data that's stored in reverse is 0, because int reverse = 0; is declared before the while loop. However, the program properly prints the reverse of the input.
import java.util.Scanner;
public class Integer {
public static void main(String[] args) {
System.out.println("This program will:");
System.out.println("1) Prompt you for an integer then \n2) List several facts about that integer");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
System.out.print("\nEnter an integer: "); // prompt the user to enter an integer
while ( ! keyboard.hasNextInt()) { // is the first input value an int?
String badInput; // assign non-integer inputs to badInput
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.print("Please enter an integer: ");
}
int integer = keyboard.nextInt(); // assign the input to the integer variable
System.out.println("A list of several facts about the number: " + integer); // safe to read first input value
System.out.println("================================================================");
// print the input with space betweeen each digits
System.out.print("a) The digit(s) in it is/are: ");
String number = String.valueOf(integer);
for ( int count = 0; count < number.length(); count++) {
char counted = number.charAt(count); // read each digit in the input
System.out.print(counted + " ");
}
System.out.println(); // skip a line
// determine whether the input is negative or positive
if ( integer >= 0 ) {
System.out.println("b) It is positive");
}
else {
System.out.println("b) It is negative");
}
// determine whether the input is even or odd
if (integer % 2 == 0) {
System.out.println("c) It is even");
}
else {
System.out.println("c) It is odd");
}
int countOdd = 0;
int countEven = 0;
int countDigit = 0;
int countZero = 0;
int reverse = 0;
int sum = 0;
int product = 1;
int readRightMost;
while(integer != 0) {
readRightMost = integer % 10; // read rightmost digit in the input
reverse = reverse * 10 + readRightMost;
integer /= 10; // drop the rightmost digit in the input
++countDigit;
sum += readRightMost;
product *= readRightMost;
if (readRightMost % 2 == 0){ // count how many even digits are in the input
++countEven;
}
else { // count how many odd digits are in the input
++countOdd;
}
if (readRightMost == 0) { // count how many zero digits are in the input
++countZero;
}
}
System.out.println("d) It has " + countDigit + " digit(s)");
System.out.println("e) It has " + countOdd + " odd digit(s)");
System.out.println("f) It has " + countEven + " even digit(s)");
System.out.println("g) It has " + countZero + " zero digit(s)");
System.out.println("h) The sum of the digits in it is " + sum);
System.out.println("i) The product of the digits in it is " + product);
if (integer < reverse) { // if the reverse value of an int is greater than its original value
System.out.println("j) It is smaller than its reverse value: " + reverse);
}
else { // if the reverse value of an int is lesser than its original value
System.out.println("j) It is bigger than its reverse value: " + reverse);
}
System.out.println("================================================================");
}
}
At the end of your while(integer != 0) loop, you know integer must be 0, and you never change it again before your if (integer < reverse), so it may as well be if (0 < reverse), which has exactly the behavior you're seeing. To fix it, make your loop operate on a different variable than you test later.

Averaging User Input, looping input until negative number is entered

import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.

How to separate a string of numbers entered in a loop?

I need help pulling the numbers out and separating them by commas, for example, if I enter 1 2 3 4 5, it should print out
Entered Numbers: 1, 2, 3, 4, 5
The Sum: 15
instead I get this
Entered Numbers: 12345
The Sum: 15
Code:
/*A program that prompts the user to enter a positive integer number. The program should accept integers until the user enters the
value -1 (negative one). After the user enters -1, the program should display the entered numbers followed by their sum*/
import java.util.Scanner;
public class InputSum
{
public static void main(String [] args)
{
//create a way to receive user input
Scanner input = new Scanner(System.in);
//Variables
int sum = 0;
String value;
//Input
System.out.println("Enter a positive integer (Enter -1 to quit): ");
value = input.nextLine();
String x = "";
//Loop Statements
while (Integer.parseInt(value) != -1)
{
sum = Integer.parseInt(value) + sum;
x = x + value;
value = input.nextLine();
}
//Output
System.out.println("Entered Numbers: " + x);
System.out.println("The sum: " + sum);
}
}
You can use replace() to do what yo want it to. Use it in this format
value = value.replace(" ", ","); //First param is the char you want to replace; The second is the one you want to replace the first param with
Replace
String x = "";
//Loop Statements
while (Integer.parseInt(value) != -1
{
sum = Integer.parseInt(value) + sum;
x = x + value;
value = input.nextLine();
}
with
String x = value;
//Loop Statements
while (Integer.parseInt(value) != -1)
{
sum = Integer.parseInt(value) + sum;
x = x + ", " + value;
value = input.nextLine();
}
Use Split string method to get each number then use trim to get stint with spaces. Then paste that string into an int and the ad it to the sum. Only the loop part has changed. everything else remains the same.
public static void main(String [] args)
{
//create a way to receive user input
Scanner input = new Scanner(System.in);
//Variables
int sum = 0;
String value;
//Input
System.out.println("Enter a positive integer (Enter -1 to quit): ");
value = input.nextLine();
for(String eachNum:value.split(",")) {
sum=Interger.parseInt(eachNum.trim());
}
//Output
System.out.println("Entered Numbers: " + value);
System.out.println("The sum: " + sum);
}

Categories