i came across this problem whereas user need to enter a certain series of number in one input, then the program will output back the number one by one. For example, the user entered 4 6 8, then the program will output 4 6 8 to the user.
The code that i have done is like this :
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int N;
String num;
Scanner in = new Scanner(System.in);
System.out.println("Enter number:");
num = in.nextLine();
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int x = 0; x < num.length(); x++)
{
char c = num.charAt(x);
if(Character.getNumericValue(c) >= 0 ){
numbers.add(Character.getNumericValue(c));
}
}
for(int n=0; n<numbers.size(); n++){
System.out.println(numbers.get(n));
}
}
}
But i think it is not really efficient as it is quite long for just doing a simple task. So, could you suggest anything that is much simpler? Thanks!
If all the numbers are in one line then this can solve the problem:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = reader.readLine().split(" ");
for (int i = 0; i < tokens.length; i++)
System.out.println(Integer.parseInt(tokens[i]));
See BufferedReader for more info.
Set delimitter on Scanner and read each number a int
Scanner in = new Scanner(System.in);
in.useDelimiter("\\s");
System.out.println("Enter number:");
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (in.hasNextInt()) {
numbers.add(in.nextInt());
}
Here's my idea:
String num = "4 6 8"; // user's input
System.out.println(num.replaceAll("\\s+", "\n"));
4
6
8
If you want to ignore everything except the numbers you can use "[^\\d]+" instead of "\\s+".
Related
package Fall21;
import java.util.Scanner;
public class BalloonRideWeight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int personWeight = sc.nextInt();
int totalWeight = 0;
for (int i=0; i<n; ++i) {
totalWeight +=personWeight;
personWeight =sc.nextInt();
}
if (totalWeight >500)
System.out.println("Everyone too fat.");
else
System.out.println("Just right.");
sc.close();
}
}
would this be a runtime issue ???
I am just learning basics so any answers with arrays and more complex levels of code are not needed.
It probably doesn't output anything because u are using Scanner which expects input. When I run your program and I enter the following input
1
1
1
I get as output
Just right.
Each of these invocations
sc.nextInt();
expects you to enter an input that gets stored in the declared variable (left hand side of the statement).
So with my first two inputs, the values
n = 1, personWeight = 1
then the loop iterates 1 time, which contains another scanner invocation setting the personWeight. Which I again set to 1.
Only then it reaches the if condition that prints something to the console. See this for more info: https://www.w3schools.com/java/java_user_input.asp
EDIT:
If you want to parse multiple ints from one line, u can do:
String[] arguments = scanner.nextLine().split(" ");
int[] ints = new int[arguments.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(arguments[i]);
}
Or a fancier version:
int[] ints = Arrays
.stream(scanner.nextLine().split(""))
.mapToInt(Integer::parseInt)
.toArray();
I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}
I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
I've been up for a few hours trying to find a solution.
My program asks the user to enter a list of integers (example: 5 2 5 6 6 1).
Then I would like to create an array and store each integer into its respective array index, consecutively.
Here is the part of my program i'm having trouble with (this program was meant to perform calculations via a method later on, but I didn't include that):
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array[x] = input.nextInt();
x++;
}
As you can see, I am instantiating the array "list1Array" but the problem is I don't know how many integers the user would enter! If only there were a way of knowing how many integers have been input... Any help would be greatly appreciated!
Thanks,
Sebastian
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//int[] list1Array = new int[1];
List<Integer> list1Array = new ArrayList<>();
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array.add(input.nextInt());
}
}
}
An ArrayList, is like an array that does not have a predefined size and it dynamically changes its size; exactly what you are looking for. You can get its size by list1Array.size();
If you insist on having the final result as an array, then you can later call the toArray() method of ArrayList. This post will be helpful.
If you really want to use Arrays, do it like this:
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()) {
list1Array[x] = input.nextInt();
x++;
int[] temp = new int[list1Array.length + 1];
for (int i = 0; i < list1Array.length; i++) {
temp[i] = list1Array[i];
}
list1Array = temp;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter elemnt size ");
int size = input.nextInt();
int x = 0;
int[] list1Array = new int[size];
for (int y = 0 ; y < size ; y++) {
System.out.println("Enter number");
list1Array[x] = input.nextInt();
x++;
}
System.out.println(Arrays.toString(list1Array));
}
Output
Enter elemnt size
4
Enter number
2
Enter number
3
Enter number
4
Enter number
2
[2, 3, 4, 2]
Use List, in your case ArrayList will be fine:
List<Integer> list1Array = new ArrayList();
while (input.hasNext()){
list1Array.add(input.nextInt());
x++;
}
You should take the input as string and then use string.split(" "); and then obtain an array of Strings representing each number. Obtaining array by string can be done by string tokenizing.
UPDATE
But you should be careful not to put other chars as separators for numbers number