Extract each seperate number from string - java

I have this as an input "1 2 3 4 5" and I want to have it like this
int[] numbers = new int[5];
number[0] = 1;
number[1] = 2;
number[2] = 3;
number[3] = 4;
number[4] = 5;
So how can I extract each number from a string and put it in an int array?
ConsoleIO io = new ConsoleIO();
int[] numbers = new int[5];
io.writeOutput("Type in 5 numbers");
String input = io.readInput();
// If input is longer than 1 character for example, "1 2 3 4 5"
if(input.length() > 1) {
System.out.println(input.length());
for(int y = 0; y < io.readInput().length(); y++) {
numbers[y] = Integer.parseInt(io.readInput().substring(y, io.readInput().indexOf(" ")));
}
return;
}
// If input is one number for example, "1"
else {
for(int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.parseInt(io.readInput());
}
}
The else works, so if I enter one number and press enter and then the next one, it's all good. But if I have a sequence of numbers with a space in between ("1 2 3 4 5") the program just breaks.

String input = io.readInput();
int[] arr = new int[5];
if(input.length() >= 5){
String[] c = input.split(" ");
for(int i = 0; i < c.length(); i++){
arr[i] = Integer.parseInt(c[i]);
}
}

Why not use a Scanner and then split and parse?
Scanner in = new Scanner(System.in);
String[] nums = in.nextLine().split(" ");
for(int i = 0; i <=5; i++) {
numbers[i] = Integer.parseInt(nums[i]);
}

Assume your input is always numbers with a space between each other (or just one number), in Java 8 you can work in this way:
String[] splits = input.split(" ");
int[] result = Arrays.stream(splits).mapToInt(Integer::parseInt).toArray();

import java.util.*;
public class Solution {
public static void main(String []args) {
Scanner in = new Scanner(System.in);
String[] nums = in.nextLine().split(" ");
int[] numbers = new int[5];
for(int i = 0; i <5; i++) {
numbers[i] = Integer.parseInt(nums[i]);
System.out.println(numbers[i]);
}
}
}

Related

How can I sum these two arrays into a new one?

How can I sum these two arrays into a new one? Where the first value of the arrayA sums the first value of the arrayB?
public class Exercises {
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
static PrintStream out = System.out;
public static void main(String[] args) throws IOException {
int numbersA[] = new int[5];
int numbersB[] = new int[5];
int numbersC[] = new int[5];
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int j = 0;
for (int i = 0; i < 5; i++) {
numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
}
{
out.print("The sum of the two arrays are: " + numbersC[j] + " ");
}
out.println();
}
}
You were pretty close. numbersA[i] and numbersB[i] (not the length of each array). Also, you don't need j and should print the prelude before the loop. Like,
out.print("The sum of the two arrays are: ");
for (int i = 0; i < 5; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
Finally, your code relies on magic numbers (hard coded array lengths). That is bad practice, instead you should use the array.length so your code doesn't require changing when your array sizes change. Like,
int[] numbersA = new int[5];
int[] numbersB = new int[5];
for (int i = 0; i < numbersA.length; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < numbersB.length; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int[] numbersC = new int[Math.min(numbersA.length, numbersB.length)];
out.print("The sum of the two arrays are: ");
for (int i = 0; i < numbersC.length; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
try to delete the numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
length from both
use this shape
numbersC[i] = numbersA[i] + numbersB[i];
i think it will be work now

Java scanner input reading

I have the following input in 3 lines:
line 1: consists of positive int m and n separated by white space
line 2: list of m int separated by white space
line 3 and beyond: list of n words separated by white space or newline character
I am unable to read beyond m and n into my code
My Code:
Scanner input = new Scanner(System.in);
m = input.nextInt();
n = input.nextInt();
int[] lines = new int[m];
String[] words = new String[n];
input.nextLine();
for (int i = 0; i < m; i++) {
lines[i] = input.nextInt();
}
for (int i = 0; i < n; i++) {
words[i] = input.next();
}
How to read the line and words into the arrays
after i call the first nextLine(), and try to read the numbers, i get a nullpointerexception
I think below is what you are looking for. Made small changes to your program. You don't really need line input.nextLine(). Hope it helps
Example Input
3 2
9 5 2
Good Luck
PROGRAM
Scanner input = new Scanner(System.in);
int m = input.nextInt();
int n= input.nextInt();
int[] lines = new int[m];
for (int i = 0; i < m; i++) {
lines[i] = input.nextInt();
}
String[] words = new String[n];
for (int i = 0; i < n; i++) {
words[i] = input.next();
}
I had the user insert the input one line at at time here. I'm not sure what you were looking for but this is what I have:
Program:
Scanner input = new Scanner(System.in);
System.out.print("Enter line 1: ");
int m = input.nextInt();
int n = input.nextInt();
System.out.println(m + " ints and " + n + " words");
System.out.print("Enter line 2: ");
int[] lines = new int[m];
String[] words = new String[n];
input.nextLine();
for (int i = 0; i < m; i++) {
lines[i] = input.nextInt();
}
System.out.print("Enter line 3: ");
for (int i = 0; i < n; i++) {
words[i] = input.next();
}
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(words));
Console:
Enter line 1: 3 4
3 ints and 4 words
Enter line 2: 1 2 3
Enter line 3: four words right here
[1, 2, 3]
[four, words, right, here]

I have to take integers in an array and output them in random order

This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}

Filling a 2D Array with user input (integer to binary)

I have to take a user input of integers from a range, convert that to binary, and fill a 3x3 array with the binary. The only problem is, my code is giving me an output of only dependent on the first 3 numbers of that binary (i.e 010001101 = 010 across all rows).
import java.util.Scanner;
public class HW11P02 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
listArray(binary);
};
public static String[][] listArray(String binary) {
String[][] array = new String[3][3];
char ch = ' ';
String value = "";
for (int i = 0; i < 3; i++) {
for (int n = 0; n < 3; n++) {
ch = binary.charAt(n);
value = Character.toString(ch);
array[i][n] = value;
System.out.print(array[i][n] + " ");
}
System.out.println();
}
return array;
}
};
I think this will provide the the output you may really want.
import java.util.Scanner;
public class HW11P02
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
int result[][]=new int[3][3];
int position=0;
for (int i = 0; i < result.length; i++)
{
for (int j = 0; j < result.length; j++)
{
result[i][j]=binary.charAt(position++)-'0';
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

Categories