Multiple systeminputs on different lines concatenated together. JAVA - java

I have "N" systeminputs each on a new line. Each line consists of three names.
I want to concatinate the lines together so i can count each word and print the word thats unique.
The systeminputs have space between them and is the following.
Input:
betsy andrew flora
carol andrew betsy
dora andrew carol
elena andrew dora
Output:
Elena
I tried putting them in a Hashset but didnt get it work because the inputs were on different lines so the output was that every word was unique.
My CODE:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();//number that defines how many inputs
int i = 0;
ArrayList<String> utopia = new ArrayList<String>();
while (sc.hasNextLine() && i <= N) {
utopia.add(sc.nextLine());
i++;
}
Plz help have tried alooot of stuff.
// A Beginner

You can try something like this to read input:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();//number that defines how many inputs
int i = 1;
List<String> utopia = new ArrayList<String>();
String line= sc.nextLine();
while (!(line = sc.nextLine()).isBlank() && i < N) {
utopia.add(line);
i++;
}
System.out.println(utopia);
You can use StringBuilder to concatenate each line. String#split(" ") method to get each word.

Related

Split long sting in new lines and check each line first word in java

I have a string that I split based on delimiter on new lines. I'm wondering now how to check the first word index[0] what word is but can't find a way to actually go trough the elements and check.
May be my approach is totally wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
int ask = 0;
for (int i = 0; i < stringArr.length; i++) {
if (stringArr[0].equals("radio")) {
ask = 10;
} else if (Objects.equals(stringArr[0], "tv")) {
ask = 15;
} else {
System.out.println("Invalid media.");
}
}
System.out.println(ask);
}
Then when I input radio 3 7210>>tv 4 2345>>radio 9 31000>>
The output should be:
10
15
10
Instead - got nothing. Empty line and the program ends.
Is something like this what you want:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
for (int i = 0; i < stringArr.length; i++) {
int ask = 0;
String[] words = stringArr[i].split(" ");
if (words[0].equals("radio")) {
ask = 10;
System.out.println(ask);
} else if (words[0].equals("tv")) {
ask = 15;
System.out.println(ask);
} else {
System.out.println("Invalid media.");
}
}
Input:
radio 3 7210>>tv 4 2345>>radio 9 31000>>
Output:
10
15
10
First of all, I defined the scanner, not sure if you did that but pretty sure you did.
The elements of stringArr will include the random numbers between each ">>". That means, in each element, we should create a new list split by " " to isolate the "radio" and "tv" as the first element.
Additionally, I just rewrote the else-if statement that checks if the first word of the phrases separated by ">>" is "tv" by using the .equals() method as your original if statement did.
Finally, since you are printing out a number EACH time the code encounters a ">>", we should print out ask inside of the for loop.
EDIT:
Moved the System.out.println(ask) inside of the if and else-if statements so it will only run with valid media.
Other than that your code worked perfectly :> , let me know if you have any further questions or clarifications!

How to separate integer inputs

I need to use scanner to get 2 inputs.
1st input is a sequence of integers that I need to store in ArrayList.
2nd input should go right after the first one and it's integer as well.
My question is - how do I stop accepting input for ArrayList and tell the machine to ask for a second number.
I ended with something like this but it does not of course work because it just keeps asking for integers for arraylist. And yes, I need to use ArrayList for the task, since I don't know how many integers there will be. I also haven't learned List interface yet so I need to use what I have in my disposal.
while (scanner.hasNextInt()) {
numbers.add(scanner.nextLine());
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
}
I managed to solve it this way, though probably not optimal
String inputString = scanner.nextLine();
String[] inputArray = inputString.split(" ");
int[] numberArray = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
numberArray[i] = Integer.parseInt(inputArray[i]);
}
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
if your input sequence is something like 23 34 54 46 then you can use this
Scanner scanner = new Scanner(System.in);
String integers = scanner.nextLine();
StringTokenizer string = new StringTokenizer(integers);
ArrayList<Integer> list = new ArrayList<Integer>();
while(string.hasNextToken()){
list.add(Integer.parseInt(string.nextToken()));
}

How to separate a string user input into two different strings?

Sorry for the uninformative title, but I'm new to Java and am quite confused about how I should separate a user input (a string) into two different strings.
Essentially, what I want to do is take a user input with two of the same numbers or letters separated by a space, and remove the corresponding numbers or letters from an ArrayList of strings.
Note: the user input can be a single number or letter, and the method for this part must identify that the user input is not a single letter or number.
For example, if I have the (java) code:
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
the user then input:5 5 (5 space 5)
and if I have an ArrayList:
Arraylist<String> arrList = new ArrayList<String>;
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
How do I remove the two 5's from arrList?
My first approach was to separate the user input string into two different strings so that I could remove the two strings from the ArrayList of strings. Since both numbers or letters should be identical to each other, I would only need to scan the first integer or letter. However, I'm not quite sure how to write a method that would scan the first integer or letter in a string that consist of two numbers/integers with a space between them.
I would be much appreciated for any help! Thanks!
Simply use Collection::removeIf method:
String number = "5"; // or an user input
arrList.removeIf(item -> number.equals(item)); // number::equals
You can use .split() to split the inputs by space
String str = scan.nextLine();
String[] list = str.split(" ");
Then you can remove inputs using .remove() from ArrayList
for (int i = 0; i < list.length; i++) {
arrList.remove(list[i]);
}
You have at least two options:
Use split():
String[] numbers = str.split(" ");
Use next() instead of nextLine():
String str1 = scan.next();
String str2 = scan.next();
If you take the latter approach, you might add a hasNext() call to handle the case where there's only one string.
According to your explained example, it looks like you only want to remove the first instance of a string item from the ArrayList otherwise you wouldn't want to supply 5 5, something like this:
String ls = System.lineSeparator();
ArrayList<String> arrList = new ArrayList<>();
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
Scanner scan = new Scanner(System.in);
String str = "";
while (str.equals("")) {
System.out.print("Enter the numerical strings to delete from ArrayList seperated by a whitespace: " + ls
+ "Your Entry: --> ");
str = scan.nextLine();
if (!str.replaceAll("\\s+", "").matches("\\d+")) {
System.out.println("Invalid Entry! Entries must be numerical integer type! (" + str + ")" + ls);
str = "";
}
}
String[] numbers = str.split("\\s+");
// Iterate through all the User Supplied numbers...
for (int i = 0; i < numbers.length; i++) {
// Remove the first instance (only) of the
// current User the supplied number.
for (int j = 0; j < arrList.size(); j++) {
if (arrList.get(j).equals(numbers[i])) {
arrList.remove(j);
break;
}
}
}
// Display the ArrayList when all is done...
System.out.print(String.join(ls, arrList));
If you supply only one 5 then only the first 5 encountered within the ArrayList is removed.

Search a text file for two strings and display how many strings are in between

How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.
String[] allWords = new String[400000];
int wordCount = 0;
Scanner input = new Scanner(new File("C:\\text.txt"));
while (input.hasNext()) {
String word = input.next();
allWords[wordCount] = word;
wordCount++;
System.out.println(wordCount);
}
Scanner sc = new Scanner(new File("C:\\text.txt"));
while(sc.hasNextLine()){
String in = sc.nextLine();
System.out.println("Enter a string:");
Scanner sc2 = new Scanner(System.in);
String str = sc2.nextLine();
System.out.println("Enter a string:");
Scanner sc3 = new Scanner(System.in);
String str2 = sc3.nextLine();
if (str.contains(str)) {
System.out.println("yes");
}
if (str.contains(str2)) {
System.out.println("yes");
}
Your math is correct. As you have surmised, subtract one from the difference of the positions. If you have any issues with the code, post your attempt to your question.
You could try something like this pseudocode.
int start
int end
a = startingString
b = startingString
String[] lines = StringFromFile.split("\n");
for(x in lines)
if(x=a)
start = position of x
for(x in lines)
if(x=b)
end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length

How to separate words by spaces?

What I'm trying to do in this code is separate each word of a five-word input into the five words that it's made of. I managed to get the first word separated from the rest of the input using indexOf and substring, but I have problems separating the rest of the words. I am just wondering what I could do to fix this.
import java.util.Scanner;
public class CryptographyLab {
public static void main (String [] args) {
fiveWords();
}
public static void fiveWords () {
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
if (i > 1) {
String clear = input.nextLine();
// I was having some problems with the input buffer not clearing, and I know this is a funky way to clear it but my skills are pretty limited wher I am right now
}
System.out.print("Enter five words: ");
String fW = input.nextLine();
System.out.println();
// What I'm trying to do here is separate a Scanner input into each word, by finding the index of the space.
int sF = fW.indexOf(" ");
String fS = fW.substring(0, sF);
System.out.println(fS);
int dF = fW.indexOf(" ");
String fD = fW.substring(sF, dF);
System.out.println(fD);
int gF = fW.indexOf(" ");
String fG = fW.substring(dF, gF);
//I stopped putting println commands here because it wasn't working.
int hF = fW.indexOf(" ");
String fH = fW.substring(gF, hF);
int jF = fW.indexOf(" ");
String fJ = fW.substring(hF, jF);
System.out.print("Enter five integers: ");
int fI = input.nextInt();
int f2 = input.nextInt();
int f3 = input.nextInt();
int f4 = input.nextInt();
int f5 = input.nextInt();
//this part is unimportant because I haven't worked out the rest yet
System.out.println();
}
}
}
The Scanner class has a next() method that returns the next "token" from the input. In this case, I think calling next() five times in succession should return your 5 words.
As Alex Yan points out in his answer, you can also use the split method on a string to split on some delimiter (in this case, a space).
You're extracting the strings incorrectly. But there is another simpler solution which I'll explain after.
The problem with your approach is that you're not supplying the indices correctly.
After the first round of extraction:
fW = "this should be five words"
sf = indexOf(" ") = 4
fS = fW.substring(0, sF) = "this"
This appears correct. But after the second round:
fW = "this should be five words". Nothing changed
df = indexOf(" ") = 4. Same as above
fD = fW.substring(sF, dF) = substring(4, 4). You get a null string
We see that the problem is because indexOf() finds the first occurrence of the supplied substring. substring() doesn't remove the portion that you substring. If you want to keep doing it this way, you should trim off the word you just substringed.
space = input.indexOf(" ");
firstWord = input.substring(0, space);
input = input.substring(space).trim(); // sets input to "should be five words" so that indexOf() looks for the next space during the next round
A simple solution is to just use String.split() to split this into an array of substrings.
String[] words = fw.split(" ");
If input is "this should be five words"
for (int i = 0; i < words.length; ++i)
System.out.println(words[i]);
Should print:
this
should
be
five
words

Categories

Resources