Java - Storing Several string inputs using a loop and input.nextline(); - java

I'm trying to get a set of string statements (which can include spaces) into a string array. The number of statements will be decided by the input of the user.
So I thought of looping the input.nextline(); function.
But I think as soon as enter is hit it is taken as \n to all the loops..
Is there any better way to do this?
Scanner input = new Scanner(System.in);
System.out.println("How many Inputs??");
numOfInputs = input.nextInt();
String[] dataStore = new String[numOfInputs];
System.out.println("Input Strings");
for(i=0;i<numOfInputs;i++){
System.out.print("Input "+(i+1)+ " = ");
dataStore[i] = input.next();
}

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many Inputs??");
int numOfInputs = input.nextInt();
String[] dataStore = new String[numOfInputs];
System.out.println("Input Strings");
for (int i = 0; i < numOfInputs; i++) {
dataStore[i] = input.next();
System.out.println("Input " + (i + 1) + " = " + dataStore[i]);
}
}
Try this . I corrected the mistakes.

Add this to the bottom after the for loop, your code is working fine:
for(String str : dataStore) {
System.out.println(str);
}

Related

Regex to validate two digits with a space in between

I want to validate the user input which should consist of two digits between 1 and 3 separated by a space. So far, the example 2 2 is matched.
Is my regex or the use I'm doing of it with !sc.hasNext() wrong to begin with?
Scanner sc = new Scanner(System.in);
System.out.println("Enter Coordinates: ");
while (!sc.hasNext("[1-3]\\s[1-3]")) {
System.out.println("Please enter right coordinates!");
sc.next();
}
String userInput = sc.nextLine();
String[] stringCords = userInput.split(" ", 2);
for (int i = 0; i < stringCords.length; i++) {
System.out.print("[" + stringCords[i] + "]" + " ");
}
int ycord = Integer.parseInt(stringCords[0]);
int xcord = Integer.parseInt(stringCords[1]);
For example, if I enter 1 1 I get this. Instead, I would like to validate it as correct and go on without being stuck in the loop.
1 1
Please enter right coordinates!
Please enter right coordinates!
Whitespace is the issue here, by default Scanner is splitting on whitespace which returns 2 values instead of one, change the default delimiter using sc.useDelimiter("\n"); and it should work.
Here is the full code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\n");
System.out.println("Enter Coordinates: ");
while (!sc.hasNext("[1-3]\\s[1-3]")) {
System.out.println("Please enter right coordinates!");
sc.next();
}
String userInput = sc.nextLine();
String[] stringCords = userInput.split(" ", 2);
}
}

How do I store tokens into their own element in a given array?

I am trying to write a method that will use StringTokenizer to break up a user inputted String by a single space and store each word into their own array. The given code is as far I have gotten before getting stuck for 3 hours. I am trying to test out the code by having the for loop print out the elements of the array but all it does is return null for every element. What am I doing wrong? My best guess is that it is not assigning the array index to a token but I am not sure.. Any help would be amazing. Thank you!
Also, I know StringTokenizer is old legacy stuff but my professor strictly stated that he wants us to use it.
Thanks
private void receiveInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
int number = st.countTokens();
String tokenArray[] = new String[number];
for (int i = 0; i < tokenArray.length; i++) {
System.out.println(tokenArray[i]);
}
}
String array tokenArray is initialized with size of tokens, but elements in the array are not assigned with values
require
tokenArray[i] = st.nextToken();
amended code
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
int number = st.countTokens();
String tokenArray[] = new String[number];
for (int i = 0; i < tokenArray.length; i++) {
tokenArray[i] = st.nextToken();
System.out.println(tokenArray[i]);
}
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

Adding the code for ascending order of user input

import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.

get input from user and store it in String Array in Java

i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}

Categories

Resources