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

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]);
}
}
}

Related

Want to print my stored names in array by JoptionPane, JAVA

public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}

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 exit a loop when user enters null

I need to write a program that prompts the user to to enter up to 5 movie titles. User to hit enter to exit input and partially fill array.
I've tried many solutions suggested in these pages. Either the loop continues or i get boolean/string conversion errors.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String [] Movie = new String[5];
String title;
int count = 0;
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
if(sc.equals("")) {
break;
}
title = sc.nextLine();
Movie[i] = title;
count++;
}
}
for(int i=0; i < Movie.length; i++) {
System.out.println(Movie[i]);
}
}
I expect the program to input code until user hits enter then see output of what was entered.
The problem is you are comparing Scanner object with empty String which is wrong sc.equals(""). First read the input into String and them check empty or not
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
title = sc.nextLine();
if(title.equals("")) {
break;
}
Movie[i] = title;
count++;
}
}
To just print an array use Arrays.toString
System.out.println(Arrays.toString(Movie));
You should not nest two loops for reading the input, you need one loop with two conditions; the count must be less than the Movies array length (which should be named movies to follow Java naming conventions) and there needs to be another line for the Scanner. I would prefer String.isEmpty() to String.equals(""). And your second loop should stop at count (since entries after that are potentially blank). Something like,
Scanner sc = new Scanner(System.in);
String[] movies = new String[5];
int count = 0;
for (int i = 0; i < movies.length && sc.hasNextLine(); i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
String title = sc.nextLine();
if (title.isEmpty()) {
break;
}
movies[count] = title;
count++;
}
for (int i = 0; i < count; i++) {
System.out.println(movies[i]);
}
import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
}
}
System.out.println(Arrays.toString(Movie));
}
}
import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
int count = 0;
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
count++;
}
}
System.out.println("Movie Titles:\n");
for(int j = 0 ; j < count; j++)
System.out.printf("%s\n", Movie[j]);
}
}

Dictionary input file and string manipulation

I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}
public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.

Reading multiple strings in 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();
}

Categories