Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi I am figuring out how to split the strings so heres my code:
because i using bufferedreader and i have two textboxes so it reads both the text boxes (the 1st textbox i type john), the second textbox i type peter) the output is johnpeter so i trying to split the textboxes instead of reading just 1 line straight.
BufferedReader reader = new BufferedReader(new InputStreamReader(
req.getInputStream()));
String name;
while ((name = reader.readLine().toString()) != null)
{
Statement stmt;
String[] players = name.split("");
String playerO = players[1];
String playerX = players[2];
Current output is:
Player 1 :j
Player 2 :o
I would like my output to be:
Player 1 :john
Player 2 :peter
As is, you won't be able to split the string where you want to, as there's no clear delimiting character. If you stored it as "john peter" or "john,peter" or something like that, it would be easier to split.
Then you would just need to change
String[] players = name.split("");
to
String[] players = name.split(" ");
or String[] players = name.split(",");
Also, as others have mentioned, remember that the first item in players is players[0], not players[1]
As others have alluded to, your original string "johnpeter" needs to instead be something like
"john,peter,joey,tom,dick,harry";
then you can
String name = "john,peter,joey,tom,dick,harry";
String[] players = name.split(",");
String playerO = players[0];
String playerX = players[1];
System.out.println("Player 1 :" + players[O]);//or, playerO
System.out.println("Player 2 :" + players[1]);//or, playerX
Note the zero-base of the array, as well. Hope this helps!
I am not sure what you trying to do since split("on what").
Try some thing like this if space between names,
String name = "john peter";
String[] players = name.split(" ");
String playerO = players[0];
String playerX = players[1];
System.out.println("Player 1 :" +playerO);
System.out.println("Player 2 :" +playerX);
If you want to split("??") there should be (split on what) identifier
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to find a way to create a program where users input their full name(first last) and that can remove multiple characters from the second character to another specific character which is the space with StringBuilder. Meaning it will print out the first initial and the entire last name.
Example:
Input:
Barrack Obama
Output:
BObama
You can either use two substrings, which will create two intermediate String objects, or you can use a StringBuilder object as follows:
String input = "Hello everyone, I'm Cho.";
String output = new StringBuilder(input).delete(5, 14).toString(); // "Hello, I'm Cho."
The code below will delete from the second character until the first space detected. For example from Dong Cho to DCho
Scanner scanner = new Scanner(System.in);
String userName;
System.out.println("Enter username");
userName = scanner.nextLine();
int spaceIndex = userName.indexOf(" ")+1;
String firstPartOfString = userName.substring(0, 1);
String lastPartOfString = userName.substring(spaceIndex, userName.length());
userName = firstPartOfString +lastPartOfString;
System.out.println(userName);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm building a project where I will take three inputs from the users: name,ID,GPA. the users should enter them in one line separated by a semicolumn";" and I want to be able to receive them as one line and be able to save them in three variables.
I'm applying a method where I will take three variables from the user. for example : the user will enter the name,Id and GPA like this:
1;Sally;90.5; //in one line separated by ";"
I want to be able to save each info from the user in different variable.
Can someone tell me how will I be able to implement that?
Here is the method:
private static void addNewStudent() {
System.out.println("enter ID;Name;Gpa; ");
String info = scanner.nextLine();
Note: I'm trying the apply the CSV in my project.
You just need read one line and then split it into string array.The input order must be ID -> NAME -> GPA:
private static void addNewStudent() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter ID;Name;Gpa; ");
String info = scanner.nextLine();
if (info != null) {
String[] infoArray = info.split(",");
if (infoArray.length == 3) {
String id = infoArray[0];
String name = infoArray[1];
String gpa = infoArray[2];
}
}
}
This should do to split the input by ";":
String[] input = GPA.split[";"];
Before trying to get the values, check if the input array has the expected size.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In Java, I am creating a program that asks the user to think of someone they know.
Then, my program asks that they enter the first letter of their first name, and the last letter of their last name, with no spaces.
I want my program to then look through an array of whole names, find the one whose first letter matches the first letter of user input, with the corresponding last letter of their last name.
here is my program so far:
import java.util.* ;
public class Guesser
{
public static void main(String[] args)
{
Scanner UserInput = new Scanner(System.in);
String [] names = {"firstname lastname " + "etc"}; //example name array
System.out.print( "Hello! I am a robot. I might be smart, but I don't know. Please play a game with me to help me see if I am smart." + "\n" + "What I want you to do is think of someone you know." + "\n" + "Enter the first letter of their first name, and the last letter of their last name. Please no spaces. Then, press enter. " );
String TheirGuess = UserInput.nextLine(); //get their input, assign a string to it
System.out.println("You entered: " + TheirGuess);
char FirstChar = TheirGuess.charAt(0); // get the the first char
char SecondChar = TheirGuess.charAt(1); // get the second char
System.out.println("I will now think of someone whose first name starts with " + FirstChar + " and last name ends with " + SecondChar );
UserInput.close();
}
}
How would I search in my string array for a name that has FirstChar as the first character and SecondChar as the last char?
This can be done in 1 line of code.
// Assuming you have populated a Set (actually any Collection) of names
Set<String> names;
List<String> matchedNames = names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.collect(Collectors.toList());
If you just want to print the matches, it's even simpler:
names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.forEach(System.out::println);
This code recognises that you can have multiple matches.
Although this may seem like spoon feeding, value to you of this answer is figuring out how it works.
The efficient way to do this would be to use two TreeSet objects. One contains Names and the other contains Last names. Then you can use subSet() method to get entries. So, example:
TreeSet<String> names = new TreeSet<>();
names.add("Antonio");
names.add("Bernard");
names.add("Peter");
names.add("Zack");
Set<String> bNames = names.subSet("B", "C");
Note, that this implementation is case sensitive. But with few adjustments you can fix it - I'm leaving this to you.
Havn't written in Java for a while, but it should go something like this:
String names[] = new String[] { "AAA BBB", "CCC DDD", "EEE FFF" };
Scanner input = new Scanner(System.in);
String userInput = input.nextLine().toLowerCase();
String result = "None";
for (String name : names) {
String[] nameSplitted = name.toLowerCase().split(" ");
if (nameSplitted[0].charAt(0) == userInput.charAt(0) &&
nameSplitted[1].charAt(0) == userInput.charAt(1)
) {
result = name;
break;
}
}
System.out.println("Result is: " + result);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm currently taking my first java class and have become completely stuck on an exercise. I'm supposed to read data from a text file containing student IDs and their corresponding test scores, have the program grade them then print the results.
I kind of understand the problem, but the book we're working from is kinda hard to read. It all blurs together and I feel like they want me to read two separate things and make a logical leap on how to put them together and I just don't get it.
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
My main issue is that I don't see how I tie the array to the data I have.
I am not gonna post the whole solution but give some steps to start.
Follow this example
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
ArrayList<String> array = new ArrayList<>();
while ((line = reader.readLine()) != null) {
array.add(line);
}
and to split the string like this
str.split(" "); // considering that ids and name are separated by spaces
So, since blanks are allowed in your list of T's and F's, which I assume means the student left the answer to the question blank, you do not have the luxury of using a convenience method like split to easily separate the answers. Instead we use our knowledge that the number of questions must be the same, and id's must have a common length. You can use the substring method to parse out the what you need.
Here's some pseudocode:
final int NUM_QUESTIONS = 25; //I didn't actually count, that's your job
final int ID_LENGTH = 8;
int currentIndex = 0;
//assuming you can fit the whole string in memory, which you should in an intro java class
//do the operations that googling "read a file into a string java" tells you to do in readFileToString
String fileContents = readFileToString("saidFile.txt");
while(fileContents.charAt(currentIndex) != fileContents.length()){
String userAnswers = fileContents.substring(currentIndex, currentIndex+NUM_QUESTIONS);
//move index past userAnswers and the space that separates the answers and the id
currentIndex = currentIndex + NUM_QUESTIONS + 1;
String userId = fileContents.substring(currentIndex, currentIndex+ID_LENGTH)
//move currentIndex past userId and the space that separates the userId from the next set of answers
currentIndex = currentIndex + ID_LENGTH + 1;
//either create an object to store the score with the userId, or print it right away
int score = gradeAnswers(userAnswers)
System.out.println(userId + " scored " + score);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i'm trying to make a questions game to try my knowledge and abilities
anyway i'm trying to use an integer to be the points and every question the user
answer gets a special amount of points anyway i was trying to do like this
switch (Ques){ case 1 : //first question about India and where it is in the map
System.out.println("in what continent India is?");
Scanner IndiaAns = new Scanner(System.in); //Scanner to receive user answer
String IndiaAns2 , IndiaAnswer ; //strings to be used to receive user input and matching with the correct ones
IndiaAns2 = IndiaAns.nextLine(); //Scanner will work here and receive...
IndiaAnswer = "asia"; //the correct answer here and will be matched with user ones
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
case 2:
System.out.println("the Appstore founds in any phone model?");
Scanner Appstore =new Scanner(System.in);
String AppstoreAns1 ,AppstoreAns2; //strings saving
AppstoreAns1 = Appstore.nextLine(); //Scanner
AppstoreAns2 = "iphone"; //matching with user answer
if (AppstoreAns1 == AppstoreAns2)
{ int Threepoints = 3; Points = +Threepoints;} else { Points = +0;}
.. there's two other case and the points integer is in not in the code sample area is in upper line any ways if the full codes its necessary i'll put it
About your code ,
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
Should be something like
if(indiaAns2.equals(indiaAnswer)){
points += QUESTION_1_POINTS;
}
Where QUESTION_1_POINTS is defined as a constant like `
public static final int QUESTION_1_POINTS =2;
There you are assigning to points variable , points + QUESTION_1_POINTS.
points += someInteger --> points = points + someInteger
Some advices,
1) Follow Java Code Conventions , variable names start with lower-case
2) For object comparision always use equals() instead of ==
Example:
Change
if (IndiaAns2 == IndiaAnswer)
to:
if (indiaAns2.equals(indiaAnswer))
3) You need to make switch statement
switch(condition){
case 1:
//code
break;
case 2:
//code
break;
default:// some code;
}