Java negative number doesn't come out positive [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Need to get that negative number to iterate from -2345 to 2 3 4 5 then it sums to 14. The part I can't figure out is the 2 3 4 5 comes out as -2 3 4 5...syntax I'm missing?? Maybe it is just a line of code or a for statement...
import java.util.*;
public class sumofNumbers{
static Scanner console = new Scanner(System.in);
public static void main(String[] args){
int input;
int sum = 0;
int strnbr = 0;
int counter = 1;
String nbr = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input)) {
input = input * (-1);
nbr = String.valueOf(input);
strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
} else {
nbr = String.valueOf(input);
strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}

Comments to your code:
if (input == (-input)) can only be true for 0 and Integer.MIN_VALUE, two fringe cases you probably don't care about. Looks like you meant if (input < 0).
input = input * (-1) is better written as input = -input.
With the above, the if and the else blocks become the same, so you only need the if to do the input = -input.
You can even do that without if by always doing input = Math.abs(input).
counter is unnecessary. You should use substring(i, i + 1) since that is what you really mean.
substring(i, i + 1).charAt(0) is the slow way to write charAt(i).
To iterate all the characters of a String, you can call toCharArray() and use an enhanced for loop.
In print(var + " ") it doesn't matter whether var is a String of one digit, a char with the digit, or an int with the digit. The result is the same.
Since nbr will only contains the characters '0' to '9', Character.getNumericValue(ch) is the slow way to say ch - '0'.
sum = sum + digit can be shortened to sum += digit.
Don't print to System.err.
Java naming convensions state that class names should start with uppercase letter.
Don't pre-declare your variables. Declare them where they are needed. This often also help reduce their scope.
Applying all of that, changes your code to:
public class SumOfNumbers {
static Scanner console = new Scanner(System.in);
public static void main(String[] args){
System.out.print("enter a number: ");
int input = console.nextInt();
System.out.print("the digits of " + input + " are: ");
String nbr = String.valueOf(Math.abs(input));
int sum = 0;
for (char ch : nbr.toCharArray()) {
System.out.print(ch + " ");
sum += ch - '0';
}
System.out.println();
System.out.println("the sum is: " + sum);
}
}
Sample output:
enter a number: -2345
the digits of -2345 are: 2 3 4 5
the sum is: 14

replace your code starting with
if (input == (-input)) {
with
System.out.print("the digits of " + input + " are: ");
input = Math.abs (input);
nbr = String.valueOf(input);
strnbr = nbr.length();
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
and delete end brackets

The main problem is in your if statement:
if (input == (-input))
That will never be true.
This simplifies your code so it isn't duplicated twice based on a negative/positive number. It could be done better, but I wanted to leave most of your code intact.
System.out.print("enter a number: ");
int input = console.nextInt();
if (input < 0) {
input = input * (-1);
}
String nbr = String.valueOf(input);
int strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
int sum = 0;
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, i + 1);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
}
System.out.println();
System.out.println("the sum is: " + sum);

Related

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.

Display int values inputted by a user on the line with spaces

I want my program to input int values from the user on the same line (e.g. 12345), and display the output with spaces between the int values(1 2 3 4 5). Please help.
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = input.nextInt();
String van = toString(num);
System.out.println("The Numbers are: " + van);
}
There are many ways, for example:
Solution 1
You can use for example String.join from Java8+, like so :
String van = String.valueOf(num);
System.out.println(String.join(" ", van.split("")));
Outputs
1 2 3 4 5
Solution 2
You can use replaceAll like this :
System.out.println(van.replaceAll(".", "$ ").trim());
for(int i = 0; i < van.length(); i++)
System.out.print(van.charAt(i) + " ");
The solution can be following
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = input.nextInt();
String value = String.valueOf(num);
String newString = "";
for (int i = 0; i < value.length(); i++) {
newString = newString + value.charAt(i) + " ";
}
System.out.println("newString=>" + newString.trim());

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);
}

Identifying if the user presses <enter>

I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement

Categories