Change Search function from String to Integers - java

This is my function that used to search String (Student Name) inside the text file. But is there any other way to change this function to search integers (Student ID) inside the text file?
String STUD_NAME;
System.out.println("ENTER STUDENT NAME: ");
Scanner name = new Scanner(System.in);
STUD_NAME = name.nextLine();
Pattern pattern = Pattern.compile("[A-Za-z]*");
if (name.hasNext(pattern)) {
FileReader fr = new FileReader("student.txt");
BufferedReader br = new BufferedReader(fr);
String s;
String keyword = STUD_NAME;
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
System.out.println(s);
}
}
} else {
System.out.println("PLEASE ENTER ALPHABETS NOT NUMBERS/SYMBOLS");
}

in your code replace "[A-Za-z]*" with "[\d]+"
This will replace your search for a string to search for integers number.
if you know exactly how many numbers is an ID you can use the following:
"[\d]{5}"
and will match an integer of 5 numbers like: 24453

Related

Extraction of string and integer from txt

I'm trying to make a simple scanner reader to read from a txt stored in C:\Users\james\Desktop\project\files\ and it's called data "data.txt", the thing is that the information stored is like this:
ASSETS 21
CHOROY 12
SHELL 9
So as you can see the spaces between the string and the integer that I want o extract are random. I was trying to make this:
public data(String s) //s is the name of the txt "data.txt"
{
if (!s.equalsIgnoreCase("Null"))
{
try {
File text = new File(s);
Scanner fileReader = new Scanner(text);
while (fileReader.hasNextLine())
{
String data = fileReader.nextLine();
String[] dataArray = data.split(" ");
String word = dataArray[0];
String number = dataArray[1];
int score = Integer.parseInt(number);
addWord(word, score);
}
fileReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
e.printStackTrace();
}
System.out.println("Reading complete");
}
But the split is only with one empty space between the string and the integer so I would like to know how can I extract that two things that are separated with any number of spaces in the same line. Example:
Line readed: HOUSE 1 -> String word = "HOUSE"; int score = "1";
Line readed: O 5 -> String word = "O"; int score = "5";
Instead of data.split(" ")
you can use
data.split("\\s+")
Also your function won't compile because it does not have any return.

Comparing a string in an array with an input string?

I am trying to make a program that reads a string from a file and split it and take a string from an array and compare it with the string that the user will input.
If they are equal then it will print it but when i use .contains in my code it prints a different string of the array that contain the word i write to compare with.
If i use .equal, it doesn't work
public static void main(String[] args) throws Exception
{
String word;
System.out.println("Enter word");
Scanner sc=new Scanner(System.in);
word=sc.next();
FileReader file =new FileReader("C:\\Users\\mypc\\Downloads\\ArabicTrans_final.txt");
BufferedReader reader=new BufferedReader(file);
String text="";
String line=reader.readLine();
while(line !=null)
{
text+=line;
line=reader.readLine();
}
String str=text;
String parts[]=str.split("-");
int no=0;
for (int i=0;i<parts.length;i++)
{
System.out.println(parts[i]);
}
for (int i=0;i<parts.length;i++)
{
if(parts[i].contains(word))
{
System.out.println("num"+i);
no=i;
}
}
String newstring[]=parts[no].split(",");
for (int i=0;i<newstring.length;i++)
{
System.out.println("You said : "+newstring[1]);
break;
}
}
}
inside text file there is some words with arabic translation that i want to show as the result of writing the english word as an input
whats,واتس-
whatsapp,واتس اب -
men,من-
yemen,يمين-
if i write whats it will show whatsapp not whats

Reading multiple lines into a scanner object in Java

I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}

Java returning entered text

My first post here on stackoverflow.
The task is:
Write a method that shall return a String, the method has no parameters. The method is going to read some word from the keyboard. The inputs ends with the word "END" the method should return this whole text as a long row:
"HI" "HELLO" "HOW" "END"
Make is so that the method return the string
HIHELLOHOW
MY CODE IS:
import java.util.*;
public class Upg13_IS_IT_tenta {
String x, y, c, v;
public String text(){
System.out.println("Enter your first letter");
Scanner sc = new Scanner(System.in); //Can you even make this outside main?
x = sc.next();
y = sc.next();
c = sc.next();
v = sc.next(); // Here I assign every word with a variable which i later will return. (at the bottom //i write return x + y + c;). This is so that i get the string "HIHELLOWHOW"
sc.next();
sc.next();
sc.next();
sc.next(); // Here I want to return all the input text as a long row
return x + y + c;
}
}
I know that my code has a lot of errors in it, I am new to Java so I would like so help and explaining of what I've done wrong. THANKS!
you can do something like this:
public String text(){
InputStreamReader iReader = new InputStreamReader(System.in);
BufferedReader bReader = new BufferedReader(iReader);
String line = "";
String outputString = "";
while ((line = bReader.readLine()) != null) {
outputString += line;
}
return outputString;
}
Probably you want something like
public String text() {
String input;
String output = "";
Scanner sc = new Scanner(System.in);
input = sc.next();
while (! input.equals("END")) {
output = output + input;
input = sc.next();
}
return output;
}
What you have done now is build a program that can only handle one specific input.
You might want to aim for something more reusable:
public String text(){
System.out.println("Talk to me:");
Scanner sc = new Scanner(System.in);
StringBuilder text = new StringBuilder();
while(!text.toString().endsWith("END"))
{
text.append(sc.next());
}
return text.toString().substring(0, text.toString().length()-3);
}
This builds a single String out of your input, stops when the String ends with "END" and returns the String without the last 3 letters ("END").

How to type in a string that will be assigned to a variable?

I need my program to ask the user to type in a String which will be assigned to a variable eg:string in the case below so the array list can be searched for a String containing the String entered by the user.
public void search(){
String string = "";
for (int i = 0; i < wordArray.size(); i++){
if (wordArray.get(i).contains(string) == true){
System.out.println(wordArray.get(i));
}
else{
System.out.println("No words match your search.");
}
}
}
If this is no gui application you can use System.in.
Scanner s = new Scanner(System.in);
String string = s.readLine();
Use the Scanner api:
Scanner s = new Scanner(System.in);
String string = s.nextLine();
....
s.close();
... or Console from System.console() :
String string = System.console().readLine();
(You need to check that you get a console back from System.console() if you want to be sure!)
here's how you read from keyboard using JavaIo
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("please type in a value ");
String str = br.readLine();

Categories