Convert int to string in a loop - java

I want to ask how to convert an int value to string while runing in loop lets say i got an int value 1 at first running of loop then i got 2 and then 3 in the end i want a string with value "123"..
your answers would be very helpful.. THANKS
int sum = 57;
int b = 4;
String denada;
while(sum != 0)
{
int j = sum % b;
sum = sum / b
denada = (""+j);
}

how to convert an int value to string
String.valueOf function returns the string representation of an int value e.g. String x = String.valueOf(2) will store the "2" into x.
lets say i got an int value 1 at first running of loop then i got 2
and then 3 in the end i want a string with value "123"
Your approach is not correct. You need variables for:
Capturing the integer from the user e.g. n in the example given below.
Store the value of the appended result e.g. sum in the example given below.
Capturing the user's choice if he wants to continue e.g. reply in the example given below.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String reply = "Y";
String sum = "";
while (reply.toUpperCase().equals("Y")) {
System.out.print("Enter an integer: ");
int n = Integer.parseInt(scan.nextLine());
sum += n;
System.out.print("More numbers[Y/N]?: ");
reply = scan.nextLine();
}
System.out.println("Appnded numbers: " + sum);
}
}
A sample run
Enter an integer: 1
More numbers[Y/N]?: y
Enter an integer: 2
More numbers[Y/N]?: y
Enter an integer: 3
More numbers[Y/N]?: n
Appnded numbers: 123
The next thing you should try is to handle the exception which may be thrown when the user provides a non-integer input.

Related

How do you make it so that when you enter a number it puts a space between each integer

import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count++;
temp = temp / 10;
System.out.print(temp + " ");
}
}
}
Need help fixing code.
Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v + " ");
temp -= v * Math.pow(10, p);
}
Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it.
Nevertheless.
You can just use a string and then split the string on each character
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c + " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
Answering solely your question, you can use this one-line code.
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
Output is: 1 2 3

Java Sum of numbers until string is entered

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

java scanner get data and detected enter each numbers and characters

I'm a beginner to the Java language. Firstly I want use a Scanner to retrieve data
For example, I enter this: 990921205 v
How can I detect the first 2 numbers for any calculation?
How can I detect each numbers for an algorithm?
I tried this:
import java.util.Scanner;
class ID2 {
public static void main(String args[]){
Scanner in=new Scanner (System.in);
int num[]=new int[3];
int A=0;
int B=0;
int C=0;
System.out.println("enter a number " +A);
}
}
With next() method of Scanner you can obtain user standard input.
String userInput = in.next();
int first = Integer.parseInt(userInput.charAt(0));
int second = Integer.parseInt(userInput.charAt(1));
//DO STUFF
Well to get the inputted values you can use Scanner.next(), but if this inputted value is an int you can also use Scanner.nextInt() to read it as an integer:
int value1= in.nextInt();
Then you will have an integer in the value1 value.
But if you are entering a string you will use the Scanner.next()to get this string and then extract the first two elements:
String s=in.next();
int firstTwoval=Integer.parseInt(s.substring(0, 2));
The answer #bigdestroyer gives this error: The method parseInt(String) in the type Integer is not applicable for the arguments (char)
You can just do it with char and not with integers at all.
For example,
Scanner input = new Scanner(System.in);
String numInput = input.next();
char nums[] = new char[numInput.length()];
for (int i = 0;i < numInput.length(); i++){
nums[i] = numInput.charAt(i);
System.out.println("For nums["+i+"] : "+nums[i]);
}
Input:
0123456789
Output:
For nums[0] : 0
For nums[1] : 1
For nums[2] : 2
For nums[3] : 3
For nums[4] : 4
For nums[5] : 5
For nums[6] : 6
For nums[7] : 7
For nums[8] : 8
For nums[9] : 9
Now since you want the first 2,3,4++ digits, you can apply the answer #chsdk gave.
If you use mine you have to parse them to integer using Integer.parseInt() to be sure that it's an actual number.

Splitting string of integers and then put the numbers onto a int array Java

Ok so i take as an input a list of numbers as a string and i want to take these numbers and create an int array with them.
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter: ");
s = input.next();
String[] parts = s.split(" ");
System.out.println(parts[1]);
for(int n = 0; n < parts.length; n++) {
System.out.println(parts[n]);
}
input.close();
}
}
Everything would be great if i could get the whole array created printed but for some reason i get this:
Input:
0 0 1 1 2 2
Output:
0
Thats it. Only the 1st element of the array is printed.Should i try to manually print and element such as parts[1](as i do and i get this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at QueueSimulation.main(QueueSimulation.java:32)
Why is this happening? And more importanly how do i fix it?
If you want to read a line, use:
s = input.nextLine();
next() returns the value till the first space.
Read more here

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources