Deletion of a particular string in a sentence
Hi ,
I have an internal table with lines of strings. Within each line i need to search for a string and delete it.. Can you help me give some ideas as to how to do this?
eg : Single line in internal table would be :
'<LS>Table fields:</> The field names and the data types of the fields'
here i need to search for '<LS>' and delete it...
how can i do this?
points will be rewarded for helpful answers
Hello,
U can do like this.
loop at itab.
if itab-lines cp '<LS>'.
delete itab.
endif.
endloop.
If useful reward.
Vasanth
Similar Messages
-
Finding a Particular string in a Database in the most Optimized way
Hi All,
Below is the query to find a Particular String in the entire database tables,I have a Database of about 500 + tables and each contains many data's .In these tables i want to find a particular
string but didn't know the column name and table name.so i did as below,but for executing this it almost take 40 - 45 minutes.Is there any other way to Optimize this and make the Query execution Faster.I am copying the code below.Please comment
DECLARE
@search_string VARCHAR(100),
@table_name SYSNAME,
@table_id INT,
@column_name SYSNAME,
@sql_string VARCHAR(2000),
@TableCount INT,
@ColumnCount INT
SET @search_string = 'Developer'
DECLARE @Tables TABLE(Rownumber int identity(1,1),name nvarchar(370),id int)
DECLARE @Columns TABLE(Rownumber int identity(1,1),name nvarchar(370),id int)
INSERT INTO @Tables
SELECT name, object_id FROM sys.objects WHERE type = 'U'
SELECT @TableCount=COUNT(1) FROM @Tables
WHILE (@TableCount >0)
BEGIN
SELECT TOP(1)
@table_name=name
,@table_id=id
FROM @Tables ORDER BY Rownumber
INSERT INTO @Columns
SELECT name,object_id FROM sys.columns WHERE object_id = @table_id AND system_type_id IN (167, 175, 231, 239)
SELECT @ColumnCount=COUNT(1) FROM @Columns
WHILE (@ColumnCount >0)
BEGIN
SELECT TOP(1)
@column_name=name
FROM @Columns
WHERE id= @table_id
ORDER BY Rownumber
--SET @sql_string = 'IF EXISTS (SELECT 1 FROM ' + @table_name + ' WHERE [' + @column_name + '] LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''
SET @sql_string = 'IF EXISTS (SELECT 1 FROM ' + @table_name + ' WHERE [' + @column_name + '] LIKE ''' + @search_string + '%'') select ''' + @table_name + ''' AS TableName , ''' + @column_name
+ ''' AS ColumnName , '''+ @search_string + ''' As SearchString'
--select (@sql_string);
--SET @sql_string = 'IF EXISTS (SELECT 1 FROM ' + @table_name + ' WHERE [' + @column_name + '] = ''' + @search_string + ''') select ''' + @table_name + ''' AS TableName , ''' + @column_name
+ ''' AS ColumnName , '''+ @search_string + ''' As SearchString'
EXECUTE(@sql_string)
SET @ColumnCount=@ColumnCount-1
DELETE FROM @Columns WHERE Name = @Column_Name
END
SET @TableCount=@TableCount-1
DELETE FROM @Tables WHERE Name= @Table_Name
ENDYou may also try the below :
http://gallery.technet.microsoft.com/c0c57332-8624-48c0-b4c3-5b31fe641c58 -
How to fill color in a cell having particular string when using convertto-html
Hello Scripters,
I have downloaded AD health check script but I am wondering if the cell color be changed for a particular string. Like all the cells having text "Failed"..should be in red color.
Here is the script-
Function Getservicestatus($service, $server)
$st = Get-service -computername $server | where-object { $_.name -eq $service }
if($st)
{$servicestatus= $st.status}
else
{$servicestatus = "Not found"}
Return $servicestatus
$Forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
[string[]]$computername = $Forest.domains | ForEach-Object {$_.DomainControllers} | ForEach-Object {$_.Name}
#Section -1
$report= @()
foreach ($server in $computername){
$temp = "" | select server, pingstatus
if ( Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue ) {
$temp.pingstatus = "Pinging"
else {
$temp.pingstatus = "Not pinging"
$temp.server = $server
$report+=$temp
$b = $report | select server, pingstatus | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Server Availability</h2>" | Out-String
#Section - 2
$report = @()
foreach ($server in $computername){
$temp = "" | select server, KDC, NtFrs, DFSR, netlogon, w32Time
$temp.server = $server
$temp.KDC = Getservicestatus -service "KDC" -server $server
$temp.NtFrs = Getservicestatus -service "NtFrs" -server $server
$temp.DFSR = Getservicestatus -service "DFSR" -server $server
$temp.netlogon = Getservicestatus -service "netlogon" -server $server
$temp.w32Time = Getservicestatus -service "w32Time" -server $server
$report+=$temp
$b+= $REPORT | select server, KDC, NtFrs, DFSR, netlogon, w32Time | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Service Status</h2>" | Out-String
#Section - 3
add-type -AssemblyName microsoft.visualbasic
$strings = "microsoft.visualbasic.strings" -as [type]
$report = @()
foreach ($server in $computername){
$temp = "" | select server, Netlogon, Advertising, Connectivity, Replication
$temp.server = $server
$svt = dcdiag /test:netlogons /s:$server
$svt1 = dcdiag /test:Advertising /s:$server
$svt2 = dcdiag /test:connectivity /s:$server
$svt3 = dcdiag /test:Replications /s:$server
if($strings::instr($svt, "passed test NetLogons")){$temp.Netlogon = "Passed"}
else
{$temp.Netlogon = "Failed"}
if($strings::instr($svt1, "passed test Advertising")){$temp.Advertising = "Passed"}
else
{$temp.Advertising = "Failed"}
if($strings::instr($svt2, "passed test Connectivity")){$temp.Connectivity = "Passed"}
else
{$temp.Connectivity = "Failed"}
if($strings::instr($svt3, "passed test Replications")){$temp.Replication = "Passed"}
else
{$temp.Replication = "Failed"}
$report+=$temp
$b+= $REPORT | select server, Netlogon, Advertising, Connectivity, Replication | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>DCDIAG Test</h2>" | Out-String
#Section - 4
$workfile = repadmin.exe /showrepl * /csv
$results = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1}
#$results = $results | where {$_.'Number of Failures' -gt 1 }
if ($results -ne $null ) {
$results = $results | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status"
$b+= $results | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-HTML -Fragment -As Table -PreContent "<h2>Replication Status</h2>" | Out-String
} else {
$results = "There were no Replication Errors"
$b+= $results | ConvertTo-HTML -Fragment -PreContent "<h2>Replication Status</h2>" | Out-String
$head = @'
<style>
body { background-color:#dddddd;
font-family:Tahoma;
font-size:12pt; }
td, th { border:1px Solid Black;
border-collapse:collapse; }
th { color:white;
background-color:DarkGoldenRod; }
table, tr, td, th { padding: 2px; margin: 0px }
table { margin-left:50px; }
</style>
$s = ConvertTo-HTML -head $head -PostContent $b -Body "<h1>Active Directory Checklist</h1>" | Out-string
$emailFrom = ""
$emailTo = ""
$smtpserver= ""
$smtp=new-object Net.Mail.SmtpClient($smtpServer)
$msg = new-object Net.Mail.MailMessage
$msg.From = $emailFrom
$msg.To.Add($emailTo)
$msg.IsBodyHTML = $true
$msg.subject="Active Directory Health Check Report From Dlhdc02"
$msg.Body = $s
$smtp.Send($msg)
Like in the Ping Status (section - 1), I'd like all the cell having text "Not Pinging" should be in RED color.
Also I am facing an issue in the (Section - 4). When the value of $Results is not null I am getting the desired output but when the value is null the text ""There were no Replication Errors"" is not getting displayed in
the HTML body. Instead it comes as "*32" (32 is the number of letters in the text).
Please help me in fixing this ....
BR
Himanshu
MCTS|MCSE|MCSA:Messaging|CCNAHere are instructions on ways to color cells based on content.
http://tech-comments.blogspot.com/2012/07/powershell-dynamically-color-posh.html
\_(ツ)_/ -
Help required- Searching Particular string in column
Hi,
I have a table by name temp and 2 values in the table. I'm using LIKE caluse to search a string. I'm getting output for some particular string. Please correct the below query for me.
I have given a table/data reference for you:
Create table temp(col1 varchar2(255));
insert into temp values ('Test_Scale_High');
1 row inserted
insert into temp values ('Test_Scale_High');
1 row inserted
commit;
select * from temp;
col1
Test_Scale_High
Test_Scale High
select * from temp where upper(col1) like '%TEST_SCALE%';
COL1
Test_Scale_High
Test_Scale High
select * from temp WHERE UPPER(COL1) LIKE '%TEST_SCALE_%';
COL1
Test_Scale_High
Test_Scale High
select * from temp WHERE UPPER(COL1) LIKE '%TEST_SCALE_H%';
No Row Selected
Thanks,
Santhosh.Ssanthosh.shivaram wrote:
select * from temp;
col1
Test_Scale_High
Test_Scale High
select * from temp where upper(col1) like '%TEST_SCALE%';
COL1
Test_Scale_High
Test_Scale High
select * from temp WHERE UPPER(COL1) LIKE '%TEST_SCALE_%';
COL1
Test_Scale_High
Test_Scale High
If I understand your requirement correctly you need to escape the Wild Card '_'
Hope the following code helps:
SQL> set feedback on;
SQL> SELECT * FROM TEMP
2 /
COL1
Test_Scale_High
Test_Scale High
2 rows selected.
SQL> SELECT *
2 FROM temp
3 WHERE UPPER (col1) LIKE '%TEST_SCALE%'
4 /
COL1
Test_Scale_High
Test_Scale High
2 rows selected.
SQL> SELECT *
2 FROM temp
3 WHERE UPPER (col1) LIKE '%TEST_SCALE\_%' ESCAPE '\'
4 /
COL1
Test_Scale_High
1 row selected.
SQL> SELECT *
2 FROM temp
3 WHERE UPPER (col1) LIKE '%TEST_SCALE_H%'
4 /
COL1
Test_Scale_High
Test_Scale High
2 rows selected.
SQL> SELECT *
2 FROM temp
3 WHERE UPPER (col1) LIKE '%TEST_SCALE\_H%' ESCAPE '\'
4 /
COL1
Test_Scale_High
1 row selected.
SQL>Regards,
Jo
Edited by: Joice John : Added 2 Sample Codes -
How to tail log files from particular string
Hello,
We would like to tail several log files "live" in powershell for particular string. We have tried to use "get-content" command but without luck because everytime as a result we received only results from one file. I assume that it was
caused by "-wait" parameter. If there is any other way to tail multiple files ?
Our sample script below
dir d:\test\*.txt -include *.txt | Get-Content -Wait | select-string "windows" |ForEach-Object {Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $_}
Any help will be appreciated.
MacBecause we want to capture particular string from that files. Application writes some string time to time and when the string appears we want to catch it and send an eventy to application log, after it our Nagios system will raise alarm.
Mac
Alright, this is my answer, but I think you won't like it.
Run this PowerShell code in PowerShell ISE:
$file1='C:\Temp\TFile1.txt'
'' > $file1
$file2='C:\Temp\TFile2.txt'
'' > $file2
$special='windowswodniw'
$exit='exit'
$sb1={
gc $using:file1 -Wait | %{
if($_-eq$using:exit){
exit
}else{
sls $using:special -InputObject $_ -SimpleMatch
} | %{
Write-Host '(1) found special string: ' $_
$sb2={
gc $using:file2 -Wait | %{
if($_-eq$using:exit){
exit
}else{
sls $using:special -InputObject $_ -SimpleMatch
} | %{
Write-Host '(2) found special string: ' $_
sajb $sb1
sajb $sb2
In this code, $file1 and 2 are the files being waited for.
As I understood you, you care only for the special string, which is in the variable $special.
All other variables, will be discarded.
Also, whenever a string equals to $exit is written to the file, the start job corresponding to that file will be terminated, automatically! (simple, right?)
In the example above, I use only 2 files (being watched) but you can extend it, easily, to any number (as long as you understand the code).
If you are following my instructions, at this point you have PowerShell ISE running, with 2 background jobs,
waiting for data being inputed to $file1 and 2.
Now, it's time to send data to $file1 and 2.
Start PowerShell Console to send data to those files.
From its command line, execute these commands:
$file1 = 'C:\Temp\TFile1.txt'
$file2='C:\Temp\TFile2.txt'
$exit='exit'
Notice that $file1 and 2 are exactly the same as those defined in P
OWERSHELL ISE, and that I've defined the string that will terminate the background jobs.
Command these commands in PowerShell Console:
'more' >> $file1
'less' >> $file1
'more' >> $file2
'less' >> $file2
These commands will provoke no consequences, because these strings will be discarded (they do not contain the special string).
Now, command these commands in PowerShell Console:
'windowswodniw' >> $file1
'1 windowswodniw 2' >> $file1
'more windowswodniw less' >> $file1
'windowswodniw' >> $file2
'1 windowswodniw 2' >> $file2
'more windowswodniw less' >> $file2
All these will be caugth by the (my) code, because they contain the special
string.
Now, let's finish the background jobs with these commands:
$exit >> $file1
$exit >> $file2
The test I'm explaining, now is DONE, TERMINATED, FINISHED, COMPLETED, ...
Time to get back to PowerShell ISE.
You'll notice that it printed out this (right at the beginning):
Id Name PSJobTypeName State HasMoreData Location Command
1 Job1 BackgroundJob Running True localhost ...
2 Job2 BackgroundJob Running True localhost ...
At PowerShell ISE's console, type this:
gjb
And you'll see the ouput like:
Id Name PSJobTypeName State HasMoreData Location Command
1 Job1 BackgroundJob Completed True localhost ...
2 Job2 BackgroundJob Completed True localhost ...
( They are completed! )
Which means the background jobs are completed.
See the background jobs' outputs, commanding this:
gjb | rcjb
The output, will be something like this:
(1) found special string: windowswodniw
(1) found special string: 1 windowswodniw 2
(1) found special string: more windowswodniw less
(2) found special string: windowswodniw
(2) found special string: 1 windowswodniw 2
(2) found special string: more windowswodniw less
I hope you are able to understand all this (the rubbishell coders, surely, are not).
In my examples, the strings caught are written to host's console, but you can change it to do anything you want.
P.S.: I'm using PowerShell, but I'm pretty sure you can use older PowerShell ( version 3 ). Anything less, is not PowerShell anymore. We can call it RubbiShell. -
How to set Multi Byte Character Set ( MBCS ) to Particular String In MFC VC++
I Use Unicode Character Set in my MFC Application ( VC++) .
now i get the output ठ桔湡潹⁵潦獵 (like this )character and i want to convert this character in english language (means MBCS),
But i need Unicode to My Applicatiion. when i change the Multi-Byte Character set It give Correct output in English but other Objects ( TreeCtrl Selection ) will perform wrongly . so i need to convert the particular String to MBCS
how can i do that ? In MFCI assume your string read from your hardware device is an plains "C" string (ANSI string). This type of string has one byte per character. Unicode has two bytes per character.
From the situation you explained I'd convert the string returned by the hardware to an Unicode string using i.e. MultibyteTowideChar with CP_ACP. You may also use mbstowcs or some similar functions to convert your string to an Unicode string.
Best regards
Bordon
Note: Posted code pieces may not have a good programming style and may not perfect. It is also possible that they do not work in all situations. Code pieces are only indended to explain something particualar. -
Delete a char from string ?
Hi,
I want to delete a char from string. i used the following function.
String f = formulla.replace('[','');
The above function doesnt work as it tells me to put a space or some char in 2nd parameter which i dont want. i just want to delete all occurences of some specific char in a string.
Any suggestion.
Thanks alot.u can do:
String before;
char charToReplace;
StringBuffer tempBuf = new StringBuffer(before);
for (int i=0; i<tempBuf.length(); i++)
if (tempBuf.charAt(i)==charToReplace)
tempBuf.deleteCharAt(i);
String after = tempBuf .toString(); HTH
Yonatan -
Bapi to mark a material for deletion in a particular plant and a particula
Hi all,
can any send me the code for bapi to mark a material for deletion in a particular plant and a particular storage location
ThnaksI would assume that it is something pretty close to this.
report zrich_0001 .
data: headdata type bapimathead.
data: plantdata type bapi_marc.
data: plantdatax type bapi_marcx.
data: sldata type bapi_mard.
data: sldatax type bapi_mardx.
data: return type bapiret2 .
data: returnm type table of bapi_matreturn2 with header line.
data: xmara type mara.
parameters: p_matnr type mara-matnr,
p_werks type marc-werks,
p_lgort type mard-lgort.
select single * from mara into xmara
where matnr = p_matnr.
headdata-material = xmara-matnr.
headdata-ind_sector = xmara-mbrsh.
headdata-matl_type = xmara-mtart.
headdata-STORAGE_VIEW = 'X'.
plantdata-plant = p_werks.
plantdata-del_flag = 'X'.
plantdatax-plant = p_werks.
plantdatax-del_flag = 'X'.
sldata-plant = p_werks.
sldata-stge_loc = p_lgort.
sldata-del_flag = 'X'.
sldatax-plant = p_werks.
sldatax-stge_loc = p_lgort.
sldatax-del_flag = 'X'.
call function 'BAPI_MATERIAL_SAVEDATA'
exporting
headdata = headdata
plantdata = plantdata
plantdatax = plantdatax
storagelocationdata = sldata
storagelocationdatax = sldatax
importing
return = return
tables
returnmessages = returnm.
check sy-subrc = 0.
Regards,
Rich Heilman -
How could I delete files with name string with "TAL" and older than 05.05.
How could I delete files with name string with "TAL" and older than 05.05.2009 on unix
Our ECC Ides system today was not responsible. For first time 17 users were working on the systtem (IWN2008/SQL2005 based). Before the people were maximally 5.
The server is done by making a homogeneous system copy from an blade machine(now it is an VIrTUAL)
There was enaught disk space. However I checked Wokload 03sdn transaction) inn system. and found out that at that time of restarting(I had to restart system 3 times to get logged on the system and even then it was almost unresponsive.
I can found in there top abap."Login_Pw", "SESSION_MANAGER", "?". (BAtch), "ADMSBUF, >DEleyed Function call, RSPOWPOO""RSWWclear", ""VA01", "SAPMHHTP "Buf Sync" >DDLOC CLEANUP)""rsbtctE"
What can I do?
¸
Who could interfer SAP_CCMS_MONI_BATCH_DPSAP_CCMS_MONI_BATCH_DP
the 2 main users under users profile were ZUGTIN running and SAPSYS( running many system jobs)
How to approach the problem -
I have an iPhone5. I updated to iOS7. Now I cannot edit my messages. I have to delete the whole message string like in iPhone 1. What has gone wrong?
Thanks it resloved my question, but Apple has made it more complicated it was so much easier to just press the edit button and select messages to be deleted. Now its cumbersome to delete several messages. Apple should give us back the edit button.
-
Prevent Resource Accounts been Deleted from a Particular Resource
Hi Everybody,
We have a situation where we want to prevent resource accounts been deleted from a particular resource when the user is deleted from IAM. All other accounts to other resources can be deleted as normal.
We are currently using version 5. Has anyone got any ideas on how to do this?
I tried modifying the target list in the Delete Users workflow but had no success so far.
Thanking you in advanced.In rev.6 we did that simply by disabling Delete action on the resource definition.
-
How to delete and edit particular line in a file and save it in same file ?
Hi,
I want to delete and edit text at particular line in a file.
But edit and delete should reflect in same file.
I have done googling for this but it results with using another file, that i dont want as i need to save changes in same file.
How can i do this?
Thanks in advance
Edited by: vj_victor on May 24, 2010 3:33 PMI just want to make sure, this is the only way to do what i mentioned ? or it could be done another way !a) write the data to a new file
b) delete the old file
c) write the data to a newer file
d) delete the new file
e) rename the newer file to the old file name.
For a hint about still more ways to do this, search for the complete lyrics of One man went to mow, Went to mow a meadow...
db -
Is there a way to delete text between two strings?
In Pages, is there a way to delete all text containted between two strings?
For example, if I have a text document that looks like this:
String 1
String 2
Unwanted text
Unwanted text
String 3
String 4
Is there was to delete the unwanted text between string 2 and 3 so it looks like this:
String 1
String 2
String 3
String 4
The unwanted text is differnet between documents but string 2 and 3 are constant. I want to do this via automator for the same strings on multiple documents.
Any help is appreciated!Do you mean Pages '09 v4.3?
There were some links here:
https://discussions.apple.com/message/24051199#24051199
Peter -
How to search for particular string in array?
I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
// ==========================================================
// Tool class
// Reads user input from keyboard and writes to text file a list of entered
// inventory items (tools)
// ==========================================================
import java.io.*;
import java.text.DecimalFormat;
public class Tool
private String name;
private double totalCost;
int units;
// int record;
double price;
// Constructor for Tool
public Tool(String toolName, int unitQty, double costPrice)
name = toolName;
units = unitQty;
price = costPrice;
public static void main( String args[] ) throws Exception
String file = "test.txt";
String input;
String item;
String addItem;
int choice = 0;
int recordNum = 1;
int qty;
double price;
boolean valid;
String toolName = "";
String itemQty = "";
String itemCost = "";
DecimalFormat fmt = new DecimalFormat("##0.00");
// Display menu options
System.out.println();
System.out.println(" 1. ENTER item(s) into inventory");
System.out.println(" 2. DELETE item(s) from inventory");
System.out.println(" 3. DISPLAY item(s) in inventory");
System.out.println();
System.out.println(" 9. QUIT program");
System.out.println();
System.out.println("==================================================");
System.out.println();
// Declare and initialize keyboard input stream
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
do
valid = false;
try
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
valid = true;
catch(NumberFormatException exception)
System.out.println();
System.out.println(" Only numbers accepted. Try again.");
while (!valid);
while (choice != 1 && choice != 2 && choice != 9)
System.out.println(" Not a valid option. Try again.");
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
if (choice == 1)
// Declare and initialize input file
FileWriter fileName = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileName);
PrintWriter dataFile = new PrintWriter(bufferedWriter);
do
addItem="Y";
System.out.print(" Enter item #" + recordNum + " name > ");
toolName = stdin.readLine();
if (toolName.length() > 15)
toolName = toolName.substring(0,15); // Convert to uppercase
toolName = toolName.toUpperCase();
dataFile.print (toolName + "\t");
do
valid = false;
try
// Prompt for item quantity
System.out.print(" Enter item #" + recordNum + " quantity > ");
itemQty = stdin.readLine();
// Parse integer as string
qty = Integer.parseInt (itemQty);
// Write item quantity to data file
dataFile.print(itemQty + "\t");
valid=true;
catch(NumberFormatException exception)
// Throw error for all non-integer input
System.out.println();
System.out.println(" Only whole numbers please. Try again.");
while (!valid);
do
valid = false;
try
// Prompt for item cost
System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
itemCost = stdin.readLine();
// Parse float as string
price = Double.parseDouble(itemCost);
// Write item cost to data file
dataFile.println(fmt.format(price));
valid = true;
catch(NumberFormatException exception)
// Throw error for all non-number input (integers
// allowed)
System.out.println();
System.out.println(" Only numbers please. Try again.");
while (!valid);
// Prompt to add another item
System.out.println();
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
// Prompt for valid input if not Y or N
System.out.println();
System.out.println(" Not a valid option. Try again.");
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
System.out.println();
// Increment record number by 1
recordNum++;
if (addItem.equalsIgnoreCase("N"))
System.out.println();
System.out.println(" The output file \"" + file + "\" has been saved.");
System.out.println();
System.out.println(" Quitting program.");
while (addItem.equalsIgnoreCase("Y"));
// Close input file
dataFile.close();
if (choice == 2)
try {
Read user input (array search string)
Search array
If match found, remove entry from array
Confirm "deletion" and display new array contents
catch block {
} // class
// ==========================================================
// ListToolDetails class
// Reads a text file into an array and displays contents as an inventory list
// ==========================================================
import java.io.*;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
public class ListToolDetails {
// Declare variable
private Tool[] toolArray; // Reference to an array of objects of type Tool
private int toolCount;
public static void main(String args[]) throws Exception {
String line, name, file = "test.txt";
int units, count = 0, record = 1;
double price, total = 0;
DecimalFormat fmt = new DecimalFormat("##0.00");
final int MAX = 20;
Tool[] items = new Tool[MAX];
System.out.println("Inventory List");
System.out.println();
System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
+ "PRICE" + "\t" + "TOTAL");
System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
System.out.println();
try {
// Read a tab-delimited text file of inventory items
FileReader fr = new FileReader(file);
BufferedReader inFile = new BufferedReader(fr);
StringTokenizer tokenizer;
while ((line = inFile.readLine()) != null) {
tokenizer = new StringTokenizer(line, "\t");
name = tokenizer.nextToken();
try {
units = Integer.parseInt(tokenizer.nextToken());
price = Double.parseDouble(tokenizer.nextToken());
items[count++] = new Tool(name, units, price);
total = units * price;
} catch (NumberFormatException exception) {
System.out.println("Error in input. Line ignored:");
System.out.println(line);
System.out.print(" " + count + "\t");
System.out.print(line + "\t");
System.out.print(fmt.format(total));
System.out.println();
inFile.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
System.out.println();
// Unfinished functionality for displaying "error" message if user tries to
// add more than 20 tools to inventory
public void addTool(Tool maxtools) {
if (toolCount < toolArray.length) {
toolArray[toolCount] = maxtools;
toolCount += 1;
} else {
System.out.print("Inventory is full. Cannot add new tools.");
// This should search inventory by string and remove/overwrite matching
// entry with null
public Tool getTool(int index) {
if (index < toolCount) {
return toolArray[index];
} else {
System.out
.println("That tool does not exist at this index location.");
return null;
} // classData file contents:
TOOL 1 1 1.21
TOOL 2 8 3.85
TOOL 3 35 6.92Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
Is that right?
Can you use an ArrayList<String> instead of a String[ ]?
To find it, you would just do:
for (String item : myArray){
if (item.equals(searchString){
// remove the element. Not trivial for arrays, very easy for ArrayList
}Heck, with an arraylist you might be able to do the following:
arrayList.remove(arrayList.indexOf(searchString));[edit]
the above assumes you are using 1.5
uses generics and for each loop
[edit2]
and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
Message was edited by:
BaltimoreJohn -
Deletion of Characters in String
Hi I having a problem. Below shows
String s = "Hello";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != 'e' && s.charAt(i) != 'o') {
System.out.print(s.charAt(i));
If I want to let user to key in the string and the program will be able to delete the 'e' and the 'o'. How do I do that?If I want to let user to key in the string Look at the Scanner class to see how you can
get user-input (through the console):
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scan
ner.html
and the program will be able to delete the 'e' andthe 'o'.
How do I do that?Look at String's replace(...) method:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Stri
ng.htmlPossible to type it out? Or complete the coding? Cos dont quite get it.
Thanks.
Maybe you are looking for
-
Material reservation and unrestricted Available qty report
Hi SAP Buddies Please can anyone tell me how to get the lCollective list of Material Reservation with Available unrestricted stock?? i.e. MAterial No. Reserve Qty Unrestricted Available Qty These three parameters are must ? Thanks
-
ICal Syncs From Exchange, but not To Exchange -- funky Console error.
I'm the IT guy troubleshooting a user's MacBook Pro 15" (not unibody) with Snow Leopard. The Mac users in my company have been having near-constant trouble with their email and calendars almost since the day they switched, first with Exchange 2003/En
-
Material In quality inspection.
Dear All, I am a SAP MM consultant and need you help. QM Proc.key was activated in material. (No inspection set up is done). PO was created. GRN Done. Material posted to quality but no Lot generated. Then some how inspection set up was done. (Dont kn
-
Can I temporarily disable a domain in Exchange?
A client has two separate companies each with a unique email domain. One has been moved to Exchange, the other is still on a GMail hosted domain while we prepare to cut them over. The company on GMail can send messages to the company on Exchange, but
-
Hi all, Having a strange issue when trying to gift an app to my brother in law. I get all the way to the end then click the 'buy' at the top right of the window, which turns it into 'buy now'. Then when I click it again it turns back into the 'buy'