With the scanner I want to read the index of a char and then remove it from the string. There is only one problem: If the char comes multiple times in the string, .replace() removes all of them.
For example I want to get the index of first 't' from the String "Texty text" and then remove only that 't'. Then I want to get index of second 't' and then remove it.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String text = "Texty text";
Scanner sc = new Scanner(System.in);
int f = 0;
int x = 0;
while(f<1){
char c = sc.next().charAt(0);
for(int i = 0; i<text.length();i++){
if(text.charAt(i)==c){
System.out.println(x);
x++;
}
else{
x++;
}
}
}
System.out.println(text);
}
}
You could use replaceFirst:
System.out.println(text.replaceFirst("t", ""));
Probably you are looking for something like the following:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "Texty text";
String copy = text;
Scanner sc = new Scanner(System.in);
while (true) {
text = copy;
System.out.print("Enter a character from '" + text + "': ");
char c = sc.next().charAt(0);
for (int i = 0; i < text.length(); i++) {
if (Character.toUpperCase(text.charAt(i)) == Character.toUpperCase(c)) {
System.out.println(c + " was found at " + i);
text = text.substring(0, i) + "%" + text.substring(i + 1);
System.out.println("After replacing " + c + " with % at " + i + ": " + text);
}
}
}
}
}
A sample run:
Enter a character from 'Texty text': x
x was found at 2
After replacing x with % at 2: Te%ty text
x was found at 8
After replacing x with % at 8: Te%ty te%t
Enter a character from 'Texty text': t
t was found at 0
After replacing t with % at 0: %exty text
t was found at 3
After replacing t with % at 3: %ex%y text
t was found at 6
After replacing t with % at 6: %ex%y %ext
t was found at 9
After replacing t with % at 9: %ex%y %ex%
Enter a character from 'Texty text':
Try using txt.substring(x,y)
x = usually 0 , but x is first start index
y = this is what you want to delete for example for the last word of string write this code:
txt.substring(0, txt.length() - 1)
Since you are specifying indices, it is possible that you may want to replace the second of a particular character. This does just that by ignoring the ones before it. This returns an Optional<String> to encase the result. Exceptions are thrown for appropriate situations.
public static void main(String[] args) {
// Replace the first i
Optional<String> opt = replace("This is a testi", 1, "i", "z");
// Replace the second i (and so on).
System.out.println(opt.get());
opt = replace("This is a testi", 2, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 3, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 4, "i", "z");
System.out.println(opt.get());
}
public static Optional<String> replace(String str, int occurrence, String find, String repl) {
if (occurrence == 0) {
throw new IllegalArgumentException("occurrence <= 0");
}
int i = -1;
String strCopy = str;
while (occurrence-- > 0) {
i = str.indexOf(find, i+1);
if (i < 0) {
throw new IllegalStateException("insufficient occurrences of '" + find + "'");
}
}
str = str.substring(0,i);
return Optional.of(str + strCopy.substring(i).replaceFirst(find, repl));
}
Related
public static void main(String args[])
{
obj.alphaSum("adam"); // I want to print "Adam" and get the same value
}
public static void alphaSum(String word)
{
String alphabet = " abcdefghijklmnopqrstuvwxyz";
int add = 0;
for(int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
int x = alphabet.indexOf(ch);
System.out.println(ch + " " + x);
add+=x;
}
System.out.println("********************");
System.out.println("Lucky Sum: " + add);
}
The uppercase "A" provides a -1 since the "A" is not listed in the String value. I want to know how I could incorperate the uppercase letters into this program.
I want to alter the code so that Adam with the uppercase "A" gives out the same index value as the lowercase "a" and give the same "Lucky Sum".
You need to convert the input word to lowercase.
public static void alphaSum(String word)
{
String lowerCaseWord = word.toLowerCase();
String alphabet = " abcdefghijklmnopqrstuvwxyz";
int add = 0;
for(int i = 0; i < lowerCaseWord.length(); i++)
{
char ch = lowerCaseWord.charAt(i);
int x = alphabet.indexOf(ch);
System.out.println(ch + " " + x);
add+=x;
}
System.out.println("********************");
System.out.println("Lucky Sum: " + add);
}
I'm writing a simple vowel-counter and was wondering if there's a cleaner alternative (possibly a loop?) to replace all of the else if's when comparing s to the various vowels.
I can't think of a simple way to do this effectively as the number of each vowel must be shown individually. It would be very simple if it was just a total vowel count.
I'm quite new to Java so I don't know what can be used to clean this up. If this is the best option, then I am contempt -- but I love cleaning up code where it can be!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int A = 0, E = 0, I = 0, O = 0, U = 0;
System.out.print("Type a single word > ");
String word = input.next();
for (int i = 0; i < word.length(); i++) {
String s = word.substring(i, i + 1);
if (s.equalsIgnoreCase("A")) { A++; }
else if (s.equalsIgnoreCase("E")) { E++; }
else if (s.equalsIgnoreCase("I")) { I++; }
else if (s.equalsIgnoreCase("O")) { O++; }
else if (s.equalsIgnoreCase("U")) { U++; }
}
int total = A + E + I + O + U;
System.out.println("\n'" + word + "' has...\n" + A + " A's\n" + E + " E's\n" + I + " I's\n" + O + " O's\n" + U + " U's\nTotal vowels: " + total + "\n");
input.close();
}
}
Input:
Coding
Output:
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
Here is a less repetitive way to code it, using an int array for the counts, and a string holding the sequence of vowels.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Type a single word > ");
String word = input.next();
String vowels = "AEIOU";
int[] counts = new int[vowels.length()];
int total = 0;
for (int i = 0; i < word.length(); i++) {
int index = vowels.indexOf(Character.toUpperCase(word.charAt(i)));
if (index >= 0) {
++counts[index];
++total;
}
}
System.out.printf("%n'%s' has...%n", word);
for (int i = 0; i < counts.length; ++i) {
System.out.printf("%s %s's%n", counts[i], vowels.charAt(i));
}
System.out.printf("Total vowels: %s%n", total);
}
}
Output:
Type a single word > Coding
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
You could avoid a lot of repetition by using a Map that associates vowels (keys) to their frequencies within the word passed at runtime (values).
It is worth noting that a LinkedHashMap is used in the below example as to preserve the insertion order of keys for printing at the end of the program - as would not be the case with a HashMap.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Define Map to map vowels to frequencies
Map<Character, Integer> vowels = new LinkedHashMap<Character, Integer>();
vowels.put('A', 0);
vowels.put('E', 0);
vowels.put('I', 0);
vowels.put('O', 0);
vowels.put('U', 0);
// Get input from user
System.out.print("Type a single word > ");
String word = input.next();
// Iterate across word
for (int i = 0; i < word.length(); i++) {
String c = word.substring(i, i+1); // Get current char
for (Character key : vowels.keySet()) { // Iterate across vowels
if (c.equalsIgnoreCase(key.toString())) {
vowels.put(key, vowels.get(key)+1); // Increment vowel frequency if matched
break; // Break inner loop and move to next char in word
}
}
// Sum total
int total = 0;
for (Character key : vowels.keySet()) {
total += vowels.get(key);
}
// Print results to console
System.out.println("\'" + word + "\'" + " has...");
for (Character key : vowels.keySet()) {
System.out.println(vowels.get(key) + " " + key + "\'s");
}
System.out.println("Total vowels: " + total);
input.close();
}
}
}
Currently stuck on an assignment that requires me to print out the users name as such: Last,First Initial.
(Bob, Billy H.) If I add too many spaces between the first and middle name when inputting, I get an index out of bounds exception. (String out of bounds 0) The program runs completely fine unless I have more than one space between the first and middle name.
I can only use the trim, indexOf, substring,and charAt methods in this program.
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", (firstSpace + 1));
middle = name.substring((firstSpace + 1), secondSpace);
middle.trim();
last = name.substring(secondSpace+1);
char middleInitial = middle.charAt(0);
String initial = "";
initial = initial + middleInitial;
for(int i = 1; i < middle.length(); i++) {
char currentLetter = middle.charAt(i);
char lastLetter = middle.charAt(i - 1);
if(lastLetter == ' ') {
initial = initial + "." + currentLetter;
}
}
System.out.println(last + "," + first + ' ' + initial + ".");
}
}
The reason for error is for input
amid skum asdf
for above input:
int firstSpace = name.indexOf(' '); //firstSpace = 0
int secondSpace = name.indexOf(" ", (firstSpace + 1));//secondSpace = 1
middle = name.substring((firstSpace + 1), secondSpace); // as the two or more continues space inputted, this will select empty string as firstSpace + 1 == secondSpace and later causing the exception
Do name = name.replaceAll(" +", " "); to replace all two or more white spaces.
As karthik suggested in comments, perform assignment middle = middle.trim();.
EDIT:
Since you can not use replaceAll, Modified the code just by using trim method. Have a closer look at the below snippets:
String middleNameLastName = name.substring(firstSpace+1).trim();
last = middleNameLastName.substring(index+1).trim();
These removes trailing spaces.
import java.util.Scanner;
public class Post1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
String middleNameLastName = name.substring(firstSpace+1).trim();
int index = middleNameLastName.indexOf(" ");
middle = middleNameLastName.substring(0, index);
last = middleNameLastName.substring(index+1).trim();
System.out.println(last + "," + first + ' ' + middle.charAt(0) + ".");
s.close();
}
}
I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.
What I have is a program that will read a text file that has data from a file that is in the format
`FootballTeamName1 : FootballTeamName2 : FootballTeam1Score : FootballTeam2Score
Currently it reads in the file and will split it at each colon what I want to know is how would I make it so that each time it comes across a name then it will add that name to the list if it doesn't already exist or if it does then it will not create a duplicate value rather it will add the values to the values that already exist for that teams name.
I currently have a program that can get the values for when you search for a team but what I want to do is make it so that it is possible when the user does not specify a team then it will make it so that it will return the results for all of the teams. Here is what I have currently which asks for the location of the file and asks the user for specifying a file which works but I'm not sure how to do what I want.
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if(!file.exists()) {
continue;
}
if(UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if ( input.equalsIgnoreCase("H") ) {
processFile(UserFile) ; }
else if ( input.equalsIgnoreCase("T")){
processFile(UserFile);
}
else{
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
//checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
int gamesplayed = 0;
int gs = 0;
int gc = 0;
int w = 0;
int d = 0;
int l = 0;
String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the team you want the results for");
String input = scanner.nextLine();
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
if ( input.equalsIgnoreCase(hteam)){
gamesplayed = gamesplayed + 1;
gs = gs + hscore;
gc = gc + ascore;
if (hscore > ascore)
w = w + 1;
else if (ascore > hscore)
l = l + 1;
else
d = d + 1;
}
else if (input.equalsIgnoreCase(ateam)){
gamesplayed = gamesplayed + 1;
gs = gs + ascore;
gc = gc + hscore;
if (hscore < ascore)
w = w + 1;
else if (ascore < hscore)
l = l + 1;
else
d = d + 1;
}
}
}
System.out.println(input + newLine + "--------------------------" + newLine + "Games played: " + gamesplayed + newLine + "Games Won: " + w + newLine + "Games Drawn: " + d + newLine + "Games Lost: " + l + newLine + "Goals For: " + gs + newLine + "Goals Against: " + gc);
}
}
If you want no duplicate elements in your collection use a Set. A Set is a collection that contains no duplicate elements (doc here).
Sounds like you want a Map from Team to Score, where if the team already exists, then get the value from the map, and and the score to that.
You can add the entries into a Set (or if you want them sorted - SortedSet). Since Set only holds unique values - you'll always have only one "copy" of each value.
For reference, the following code uses 5 values, but the set will have only 3 (unique) values:
String str = "A : B : C : B : A";
String[] vals = str.split(":");
SortedSet<String> myVals = new TreeSet<String>();
for(String val : vals)
{
myVals.add(val.trim());
}
System.out.println("Set size: " + myVals.size());