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());
Related
I keep getting an error with my code specifically at
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
the error tells me "; expected" what am I doing wrong here?
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = 0;
numLines = scnr.nextInt();
System.out.println();
ArrayList lines = new ArrayList();
scnr.nextLine();
int i = 0;
do{
System.out.println("Enter your text: ");
String text = scnr.nextLine();
ArrayList<String> input = new ArrayList<String>();
i++;
for (i = 0; i < numLines; i++)
{
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
}
for (String element: ArrayList<String> Lines)
{
System.out.println(element);
}
} while(i != 0);
As you have
ArrayList<String> input = new ArrayList<String>();
within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do
Next, to add to this loop, use add method
String text = scnr.nextLine();
input.add (text);
To simplify, you do not need a do as you have a number of times that you want to loop
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = scnr.nextInt();
System.out.println();
scnr.nextLine();
ArrayList <String> lines = new ArrayList <> ();
for (int i = 0; i < numLines; i++) {
System.out.println("Enter word...");
String text = scnr.nextLine();
lines.add(text);
}
To print your list, you can then do
for (int x = 0; x < lines.size(); x++) {
System.out.println (lines.get(x));
}
output
how many lines of text do you want to enter
5
Enter word...
one
Enter word...
two
Enter word...
three
Enter word...
four
Enter word...
five
one
two
three
four
five
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);
For example, the user enters "1 2 3 4", how do I extract those four numbers and put them into separate spots in an array?
I'm just a beginner so please excuse my lack of knowledge.
for (int i = 0; i < students; i++) {
scanner.nextLine();
tempScores[i] = scanner.nextLine();
tempScores[i] = tempScores[i] + " ";
tempNum = "";
int scoreCount = 0;
for (int a = 0; a < tempScores[i].length(); a++) {
System.out.println("Scorecount " + scoreCount + " a " + a );
if (tempScores[i].charAt(a) != ' ') {
tempNum = tempNum + tempScores[i].charAt(a);
} else if (tempScores[i].charAt(a) == ' ') {
scores[scoreCount] = Integer.valueOf(tempNum);
tempNum = "";
scoreCount ++;
}
}
You can use String.split(String) which takes a regular expression, \\s+ matches one or more white space characters. Then you can use Integer.parseInt(String) to parse the String(s) to int(s). Finally, you can use Arrays.toString(int[]) to display your int[]. Something like
String line = "1 2 3 4";
String[] tokens = line.split("\\s+");
int[] values = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
values[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(values));
Outputs
[1, 2, 3, 4]
If you are very sure that the numbers will be separated by space then you could just use the split() method in String like below and parse individually :
String input = sc.nextLine(); (Use an sc.hasNextLine() check first)
if (input != null || !input.trim().isEmpty()) {
String [] numStrings = input.split(" ");
// convert the numbers as String to actually numbers by using
Integer.parseInt(String num) method.
}
I'm working on a java assignment and was stuck on this part. Basically we are to get the user to input three positive non-zero integers using the scanner.
It's supposed to look something like this
Enter three integer values: 2 2 10
The numbers (2, 2, 10) cannot form a triangle.
I was wondering how can I code it so that entering the "2 2 10" could be read as three different integers that are separated by a comma. Thank you very much in advance.
Read the input with java.util.Scanner and a for loop:
Scanner sc = new Scanner(System.in);
int[] values = new int[3];
for (int i = 0; sc.hasNextInt() && i < 3; i++) {
values[i] = sc.nextInt();
}
Try this:
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] inValues = line.split(" ");
int[] values = new int[inValues.length];
for(int i = 0; i < inValues.length; i++){
values[i] = Integer.parseInt(inValues[i]);
}
scanner.nextInt is your answer
final BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));
// enter yours 2 2 10 and press Enter
final String line = input.readLine();
final Scanner s = new Scanner(line);
int a = s.nextInt(); // reads 2
int b = s.nextInt(); // reads 2
int c = s.nextInt(); // reads 10
if (a + b > c || a + c > b || b + c > a ) {
System.out.println(
"No triangle can be composed from " + a + ", " + b + ", " + c );
}
You can make it as follows:
String sentence = scanner.nextLine();
And you can make:
String[] splittedByComma = sentence.split(",");
Or by space:
String[] splittedBySpace = sentence.split(" ");
Or an array list like the following example:
How to split a comma-separated string?
Then parse each of them to integers.
How do I enter a digit like '23423' and output it like '2 3 4 2 3'? And how do I make it so that user cannot enter less or more than 5-digits?
(Your help would be appreciated. I just need hints from you guys since I'm learning Java. Looking forward to learn something new.)
This is what I have so far:
Scanner input = new Scanner(System.in);
int value1, value2, value3, value4, value5;
System.out.print("Enter a number: ");
value1 = input.nextInt();
System.out.print("Enter a number: ");
value2 = input.nextInt();
System.out.print("Enter a number: ");
value3 = input.nextInt();
System.out.print("Enter a number: ");
value4 = input.nextInt();
System.out.print("Enter a number: ");
value5 = input.nextInt();
System.out.printf(" %d " + " %d " + " %d " + " %d " + " %d\n ", value1, value2, value3, value4, value5);
It can be redone with a loop: make the loop read the input 5 times and, each time, put the i-th read value at the i-th position of an array.
Then, to print it, you can just use a for loop that prints each element of the array.
If you really want them to enter a single 5 digit number, you're going to have to do validation on the users input and then give an error if the input isn't valid. If the requirements are such that the first digit of your 5 digit number should never be zero, you can just get an int and then check if it is greater than 9999 and less than 100000. Otherwise take it as a string and check the length, then turn it into an integer once you have validated it.
The most appropriate solution seem to me a while loop where you build a string and add a space. In the aftermath of the while processing you should eliminate the last space. Something like the following should fit your needs. I have used the apache commons project, but you also utilize your own class.
Scanner scanner = new Scanner(System.in);
String str = "";
while (scanner.hasNext()) {
String next = scanner.next();
if (next.equals("E")) {
break;
}
if (NumberUtils.isNumber(next)) {
for (int i = 0; i < next.length(); i++) {
str += Integer.valueOf(next.substring(i, i + 1)) + " ";
}
}
}
str = str.substring(0, str.length() - 1);
System.out.println("your number: " + str);
With "E" you can exit the loop.