Reading multiple strings in java - java

I have to read strings from the user based on a number n and store n strings in n different variables. I'm stuck with how to put them into different strings. Please help me out.
This is my code:
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
for (int i=0; i<=b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
So if b = 5, i have to input 5 strings from the user and store them in 5 different string variables. I'm able to take it from the user but not able to assign them into different variables. Can u please help me out?
Thanks.

If you know exactly the number of input then use an Array, if not use a ArrayList
With Arrays
String []inpupts = new String[b];
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs[i] = in.nextLine();
}
With ArrayList
List<String> inpupts = new ArrayList<String>();
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs.add(in.nextLine());
}

From your code (<= b) I am assuming you just started learning Java. Therefore, I edited your solution and am proposing the following, if this is okay?
public static void main(String[] args) {
int b;
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
//necessary to do due to Enter key pressed by user
in.nextLine();
String s[] = new String[b];
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s[i] = in.nextLine();
// You can check at the same time if this is what you entered
System.out.println("I have received this sring: "+s[i]+"\n");
}

Create an array and store it in an array like below:
String s[] = new String[b];//use b+1 if you need b+1 entries
for (int i=0; i<b; i++) {//use <=b is you need b+1 entries
System.out.println("Enter a string: ");
s[i] = in.nextLine();
}
You can then access your values as:
for (int i=0; i<b; i++) //use <=b is you need b+1 entries
System.out.println("Entered string was : " + s[i]);
}

Solution :
You can use something like this.
You can change your code as :
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
in.nextLine(); // To get a new line
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}

Related

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

How do I store the user input that is indented by a space into the String array and convert the number into int array?

I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class

Why do I always get to enter a-1 strings in this string array?

Why do I always get to enter a-1 strings in this string array?
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Declare the variable
int a;
// Read the variable from STDIN
a = in.nextInt();
String strs[]=new String[a];
for(int i=0;i<a;i++)
strs[i]=in.nextInt();
}
}
You can change condition in your loop, like this :
for (int i = 0; i < a - 1; i++) {
strs[i] = in.nextInt();
}
You are iterating correctly a number of times equal to a. Not a-1. So the question appears to be invalid:
public class Source {
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
// Declare the variable
int a;
System.out.print("How many Strings would you like to enter? ");
// Read the variable from STDIN
a = in.nextInt();
String[] strs = new String[a]; // this will fail for certain values of `a`
for(int i=0; i<a; i++) {
System.out.format("Enter String number %d: ", i+1);
strs[i]= in.next();
}
System.out.println("Result: " + Arrays.toString(strs));
}
}
}
run:
How many Strings would you like to enter? 2
Enter String number 1: Apple
Enter String number 2: Pen
Result: [Apple, Pen]

Java: How do I replace a string element from an array

Im a newbie in java programming and I'm trying to create a program wherein the user will be asked to input words into an array depending on the number specified by the user. Afterwards, the program will be displaying the entered words in Alphabetical order. The user will also be prompted "Which word to replace from the list?" This is the part I'm having problems. I dont know how the user can enter the new word (a string element) and replace it from the list. What I was able to come up, is to input an integer representing the position of that word from the array and replace it from the list. Dont know how can I make it as string?
import java.util.Scanner;
import java.util.Arrays;
public class EnterArrays {
public static void main ( String args[] ){
int length;
Scanner sc = new Scanner(System.in);
Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = an.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}
Break your code up into smaller methods. See the (working) example below. All you need to do to change the word (string, not numeric index) with another is loop through and check for equality with the equals method. The break statement after that will stop iteration (after you've found the correct index, no point looking further).
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
Sample output:
How many words are you going to enter? 5
Enter word 1:apple
Enter word 2:banana
Enter word 3:orange
Enter word 4:pear
Enter word 5:lemon
Your words are:
apple
banana
lemon
orange
pear
Which word would you like to change? banana
You have chosen to change the word : banana
Enter the new word: strawberry
Your words are:
apple
lemon
orange
pear
strawberry
Replace the code between
System.out.println("Which word would you like to change?");
and
System.out.println("You have chosen to change the word : " +
sWordToChange);
with this:
sc.nextLine();
String sWordToChange = sc.nextLine();
int index=-1;
for (int i = 0; i < sEnterWord.length; i++) {
if(sEnterWord[i].equals(sWordToChange))
index=i;
}
Explanation:
The first line is just to avoid the scanner skipping the assignation to sWordToChange. The for loop iterates over the array and looks for a match, if it finds one it saves the index of the word on the previously declared variable index. It is initalized as -1 in case the word is not found. Maybe you want to add an if block right after the substitution to make sure you modify the array only when there is a match
Changed the Scanner class to BufferedReader Class.
public class ArrayTest {
public static void main(String args[]) throws IOException {
int length;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many words are you going to enter? ");
length=Integer.parseInt(br.readLine());
String[] sEnterWord = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println("Enter word " + (nCtr + 1) + ":");
sEnterWord[nCtr]=br.readLine();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
for (int i = 0; i < sEnterWord.length; i++) {
if (sEnterWord[i].equals(sWordToChange)) {
sEnterWord[i] = sNewWord;
}
}
System.out.println("Your words are: ");
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
}}
you can also make some changes in the code like:
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
int position = Arrays.binarySearch(sEnterWord, sWordToChange);
if (position < 0) {
System.out.println("Word not found ");
} else {
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
sEnterWord[position] = sNewWord;
}
In this program you need add sc.nextLine() before taking new word to update in String array.nextLine() method of Scanner class takes empty string from buffer.
The whole program with change of code.
package expertwebindia;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]){
int length;
Scanner sc = new Scanner(System.in);
//Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
sc.nextLine();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = sc.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}

Finish input to array before printing all

I am trying to do input to an array until it is full and after that print the entire array. But I cannot get the loop to run until the array is full and after that print all.
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++){
course[i] = input.next();
grade [i] = input.nextInt();
if (i == course.length)
break;
//System.out.println("\nHow do you want to order course and grade?");
//System.out.print(" 1 - Ascending?\n"
// + " 2 - Decending?\n");
//System.out.println("Name and grade is " + course[i] + " " + grade[i]);
System.out.println(Arrays.toString(course)+(grade));
}
}
}
How can get the loop to run and then jump to the print statement?
the variable i in the loop can never be equal to course.length because the loop runs only until i < course.length. So the if block is redundant anyway.
The printing statement should be AFTER the for block, otherwise you'd be printing the array in each iteration.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade [i] = input.nextInt();
}
System.out.println(Arrays.toString(course)+(grade));
}
There should be a } after grade [i] = input.nextInt();.
And the following if is not necessary at all.
It seems the loop would do the job if it was closed after the two assignment statements. The check afterwards isn't useful and could be removed.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[2]; // creating array
int[] grade = new int[2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade[i] = input.nextInt();
}
System.out.println(Arrays.toString(course) + (grade));
}
if (i == course.length) is unnecesery because when i == length then for loop finish working and for-loop-body doesn't call so remove this line and put instead of it close loop "}"
Next is printing your array. Change the last line to:
System.out.println(Arrays.toString(course) + Arrays.toString((grade)));

Categories