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

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

Related

Trouble printing an int value user entered

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

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}

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.

Java. Turning integer values into String using the scanner

I have created a program that uses the Scanner to ask the user for int values until they insert -1 which makes the program to stop receiving numbers. After doing so, it will add all the values entered by the user. This is my code so far:
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
String string = Integer.toString(value);
while (value != -1)
{
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
string = Integer.toString(value);
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + string + ",");
System.out.println ("The sum is " + sum);
}
}
I want the output to look like this:
Entered numbers: 1,2,3,4,5 //example of number the user might enter
The sum is 15
I wanted to use a String for it to give me the sets of entered numbers, but it only gives me the last entered value. Which is -1 because that is the number that has to be entered to stop the program.
How can I out this problem?
In your
while(value != -1){
...
string = Integer.toString(value);
}
you are replacing string value with new one, so old value is lost. You should add new value to previously stored one. So your code may look like
string = string + "," + value;
You should also place this code before handling value which will be -1.
BTW, when you will learn more about Java you will know that each time you call
string + "," + value
new String is being created. Such string will need to copy content of other chunks. which may be very inefficient in case of long strings. To optimize this we can use StringBuilder and append new parts to it in loop.
In Java 8 we can also use StringJoiner which can automatically add prefixes, delimiters and suffixes for us.
Simply use string += "," + Integer.toString(value); This will give you a comma separated list of all the values you have entered. Your current statement string = Integer.toString(value); causes the variable string to be reset to the string representation of "value" for every iteration.
Check this code.
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
StringBuilder sb = new StringBuilder();
while (value != -1)
{
if(sb.length() == 0){
sb.append(value);
}else{
sb.append(","+value);
}
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + sb.toString());
System.out.println ("The sum is " + sum);
}
}

Categories