I need user input 3 names separated by space, for example:
Please enter 3 names: name1 name2 name3
then I want to store it to array with 3 string elements as those 3 names, How to do that, please suggest me some method of STRING in java since I'm often use C++, I'm not asking for code, thank you!
String array[] = new String[3];
System.out.print("Please enter 3 names: ");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
//do domething
This is a perfect place for
String.split()
Scanner has a method named next that gives you next word* instead of next line. That should be a sufficient hint.
* Not entirely true. The default delimiter is whitespace. If you change that, you would be getting tokens separated by that particular delimiter.
Another way: Just split the string by supplying the characters to be used for splitting.
"hello j and k".split(" ") => { "hello", "j", "and", "k" }
String array[] = new String[3];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++)
{
String input = in.nextLine();
array[i] = input;
}
Related
How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());
Ive been writing a program that is able to calculate a person's grades, but Im unable to turn a string into an String array (it says the array length is 1 when i put in 3 words). Below is my code. Where am I going wrong??
protected static String[] getParts(){
Scanner keyboard = new Scanner(System.in);
System.out.println( "What assignments make up your overall grade? (Homework, quizzes, etc)" );
String parts = keyboard.next();
Pattern pattern = Pattern.compile(" ");
String[] assignments = pattern.split(parts);
// to check the length
for ( int i = 0; i < assignments.length; i++ )
System.out.println(assignments[i]);
return assignments;
}
Scanner::nextLine
Scanner::next() only consumes one word (it stops at whitespace). You want Scanner::nextLine, which consumes everything until the next line, and will pick up all your words.
Use keyboard.nextLine instead:
static String[] getParts()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What assignments make up your overall grade? (Homework, quizzes, etc)");
String[] assignments = keyboard.nextLine().split(" ");
for (String i : assignments)
System.out.println(i);
return assignments;
}
NOTE: You also do not need to define a Pattern. You also do not need to return anything since the method already prints the strings. Unless of course you plan on using the values elsewhere
In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.
import java.util.Scanner;
class reverseString{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
int length = input.length();
String reverse = "";
for(int i = length - 1; i >= 0; i--){
/*if(input.charAt(i) == ' '){
reverse += " ";
}
*/
reverse += input.charAt(i);
}
System.out.print(reverse);
}
}
Can someone please help with this, thank you.
Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change
String input = scan.next();
to
String input = scan.nextLine();
You can also initialize the Scanner this way:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
So that it delimits input using a new line character.
With this approach you can use sc.next() to get the whole line in a String.
Update
As the documentation says:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
An example taking from the same page:
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
All this is made using the useDelimiter method.
In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I realise it's pretty basic.
I need to ask user for an string input. Then I divide string to single char array and print it in a console. I have to ignore spaces
Tried this but when I input "this is test string" as output I get only {t h i s}
String tekst;
Scanner odczyt = new Scanner(System.in);
System.out.println("Wpisz tekst");
tekst = odczyt.next();
int iloscZnakow = tekst.length();
char tablica[] = new char[iloscZnakow];
tablica = tekst.toCharArray();
System.out.println(Arrays.toString(tablica));
You can use toCharArray() method of String class.
Please replace odczyt.next(); with odczyt.nextLine();