Replace java giving 2 strings - java

Well as you can read, when i use the replace function in my code it prints out:
Hey, I'm.
Hey, (name).
When it should only print out Hey, (name).
And i dont understand why. Here is the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fiestaaburrida;
import java.util.Scanner;
/**
*
* #author xBaco
*/
public class FiestaAburrida {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner teclado = new Scanner(System.in);
int times = teclado.nextInt();
int index = 0;
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
}
}

Scanner.next() will read your input up to the next delimeter, which by default is a space. Because of this, you are getting two inputs, I'm Joe, rather than the one input I'm Joe.
If you want to take in an entire line at once, you should use Scanner.nextLine(). (Though you should watch out for this quirk which will affect you because of your first nextInt.)

It is because teclado.next(); fetches the next value in the console that is separated by a space. You want to use teclado.nextLine();. Although this is not a complete fix. If you were to follow up with this approach and enter "I'm Jake", than the program would print "Hey, ." followed by "Hey, Jake". This is because you are using teclado.nextInt();, which works, but it will not cause Scanner#nextLine() to read "I'm Jake" immediately. Thus you must also replace nextInt(); with nextLine(); and parse it:
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int times = Integer.parseInt(teclado.nextLine());
int index = 0;
while (index < times){
String greeting = teclado.nextLine();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, " + newgreeting + ".");
}
}

Java's String.replace method find one string and replace the one.
So, I recommend you use String.replaceAll
// ....
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replaceAll("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
// ....

Related

Am I overcomplicating a simple solution in Java?

For my Java homework I need to create a script that returns the first word within a string, and, as a part two, I need to also return the second word. I'm currently working on the first part, and I think I'm close, but I'm also wondering if I am over complicating my code a bit.
public static void statements(){
Scanner userInput = new Scanner(System.in);
char [] sentenceArray;
String userSentence;
char sentenceResult;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
for(int x = 0; x < userSentence.length(); x++){
sentenceResult = userSentence.charAt(x);
sentenceArray = new char[userSentence.length()];
sentenceArray[x] = sentenceResult;
if(sentenceArray[x] != ' '){
System.out.print(sentenceArray[x]);
//break; This stops the code at the first letter due to != ' '
}
}
}
I think I've nearly got it. All I need to get working, for the moment, is the for loop to exit once it recognizes there is a space, but it prints out the entire message regardless. I'm just curious if this can be done a little simpler, as well as maybe a hint of what I could do instead, or how to finish.
Edit: I was able to get the assignment completed by using the split method. This is what it now looks like
public static void statements(){
Scanner userInput = new Scanner(System.in);
String userSentence;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
String [] sentenceArray = userSentence.split(" ");
System.out.println(sentenceArray[0]);
System.out.println(sentenceArray[1]);
}
}
As it is your homework, I would feel bad to give you code and resolve it for you.
Seems like you really overcomplicated that, and you are aware, so it's good sign.
I need to create a script that returns the first word within a string,
and, as a part two, I need to also return the second word
So, you have a String object, then check yourself the methods of that class.
It is possible to solve it in 2 lines of code, but:
you must be aware of one special method of String class, the most useful will be one that could somehow split the string for you
you need to have some knowledge about java regular expressions - words are separated by space
after you split the string, you should get an array, accessing first and second element by index of an array will be sufficient
Personally, I think you are overthinking it. Why not read in the whole line and split the string by whitespaces? This isn't a complete solution, just a suggestion for how you can get the words.
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a complete sentence: ");
try {
String userSentence = reader.readLine();
String[] words = userSentence.split(" ");
System.out.println(words[0]);
System.out.println(words[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here's how I'd do it. Why not return all the words?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Add something descriptive here.
* User: MDUFFY
* Date: 8/31/2017
* Time: 4:58 PM
* #link https://stackoverflow.com/questions/45989774/am-i-over-complicating-a-simple-solution
*/
public class WordSplitter {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("Sentence: %s", arg));
List<String> words = getWords(arg);
System.out.println(String.format("# words : %d", words.size()));
System.out.println(String.format("words : %s", words));
}
}
public static List<String> getWords(String sentence) {
List<String> words = new ArrayList<>();
if ((sentence != null) && !"".equalsIgnoreCase(sentence.trim())) {
sentence = sentence.replaceAll("[.!?\\-,]", "");
String [] tokens = sentence.split("\\s+");
words = Arrays.asList(tokens);
}
return words;
}
}
When I run it with this input on the command line:
"The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!"
Here's the result I get:
Sentence: The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!
# words : 12
words : [The, quick, agile, beautiful, fox, jumped, over, the, lazy, fat, slow, dog]
Process finished with exit code 0

How to put keyboard input values into an array using a loop?

Here I was trying to get two keyboard inputs from the user into a single array index position.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tour;
import java.util.Scanner;
import tour.City;
/**
*
* #author dp
*/
public class Tour {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
City[] city = new City[9];
Scanner in = new Scanner(System.in);
for(int i=0;i<city.length;i++)
{
int no = in.nextInt();
String name = in.nextLine();
city[i]= new City(no,name);
}
}
}
When I run this code it'll give me the following exception.
I'm very new to java and don't know how to solve this.
Since 12 and NY are on different lines, when you do
String name = in.nextLine();
the String that you get back is empty. This is because the Scanner's "reading point" is positioned after 12, but before the end-of-line marker that follows it.
You can fix this by adding another nextLine, and dropping its result:
in.nextLine(); // Skip to end-of-line after the number
String name = in.nextLine();
You are using nextInt() and nextLine() methods to read user inputs, these methods read the next available token, so this is how the existing code is working:
It reads a number using nextInt() and assigns it to no
User then hits return and control reads an empty line (as next line is empty) and assigns it to name
City object gets created with 12 as no and <empty_string> as name. For loop starts it's second execution.
By this time, user has typed NY and hits return
As it expects the token to be an int (by calling nextInt()), it fails and throws an Exception.
If you want the control to read the two inputs separately (and wait until user hits return), use:
int no = Integer.parseInt(in.next());
String name = in.next();
just need to read the int to the last of line
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tour;
import java.util.Scanner;
import tour.City;
/**
*
* #author dp
*/
public class Tour {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
City[] city = new City[9];
Scanner in = new Scanner(System.in);
for(int i=0;i<city.length;i++)
{
int no = in.nextInt();
in.nextLine();//read to the end of line
String name = in.nextLine();
city[i]= new City(no,name);
}
}
}

Putting 2 Public Classes within one code

Can I put 2 public classes into one Java code?
For example: I need to turn an inputted word backwards, and then the user can ask to print out an individual character.
I have the first part of the code written, where it changes the word to be backwards, but am not sure how to implement the second part of the code within the first.
import java.util.*;
class backwards_string
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
reverse = reverse.toUpperCase();
System.out.println("Your word backwards is: "+reverse);
System.out.println("Choose an individual character to print out: ");
}
}
If the question is: how many top-level (= NOT nested) classes may I have in a single java file?
The answer is: you can have only one top-level class with the public access modifier. Also, in this case the file name has to match the name of the public class within it.
Anyway, peeking at your code:
class backwards_string {
//...
}
The class backward_string is not public, it's default (the access level you obtain when you do not declare any access modifier at all). Therefore you may have as many top-level default classes as you like within the same java file.
If you really want to have more than one public top-level class, then each one has to have its own file source.
Yes, this is possible. You don't have to put it in one file though, you can use different classes. They would have to be in the same package (folder) though.
It would look something like this:
backwards_string.java
import java.util.*;
class backwards_string
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
reverse = reverse.toUpperCase();
System.out.println("Your word backwards is: "+reverse);
System.out.println("Choose an individual character to print out: ");
//when you want to use the other class:
DifferentAction_String otherClass = new DifferentAction_String();
otherClass.doThingsWithReverseString(reverse);
}
}
DifferentAction_String.java:
public class DifferentAction_String {
public void doThingsWithReverseString(String reverse) {
//here you do things with the reverse string.
}
}

Taking Portions of a String

I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

Categories

Resources