Copy a string of words to an array in Java - java

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

Related

Java input/output confusion

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.

double print before allowed to respond

I'm still new to programming and have been trying to learn how to fix this code
im trying to input and record a username and password depending on how many users I input, but when i run it it prints out the "whats your username?" question twice before i'm allowed to give a response. I've narrowed the problem down to the user[i]=in.nextLine() part
public static void main(String[] args){
System.out.println("How many Users?");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
String[] user;
user = new String[x];
String[] pass;
pass = new String[x];
for(int i=0; i<x;i++){
System.out.println("What is your Username?");
user[i] = in.nextLine();
Add in.nextLine(); after int x = in.nextInt(); to consume and ignore the new line character left over by call to nextInt()
When you use a scanner it consume only the bytes needed for the requested token.
If the first call is to get the number of users (nextInt) it reads only the minimum number of digits composing it and leave the \n (new line character) not consuming it.
Because you are asking for the next line on the loop the first nextLine use only the \n.
So the best solution to make your code correct is to add a
in.nextLine();
before the for loop.

Prompt user for inputs and then sort alphabetically?

I'm currently in my first semester. I have a project requiring me to build a program having a user input 3 words, sort them alphabetically and output the middle word. I have done some searching and seem to only come back with results for sorting 2 words. I so far have code to get the user input but I am completely lost as to how to sort them alphabetically and how to prompt the user to enter the three strings. Please be patient with me as I am very new to programming. If anyone can provide me with any advice or the best or easiest way to go about sorting these I would greatly appreciate it
import java.util.Scanner; //The Scanner is in the java.util package.
public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.
String str1, str2, str3;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
str1=input.next(); //Sets "str1" = to first word.
str2=input.next(); //Sets "str2" = to second word.
str3=input.next(); //Sets "str3" = to third word.
System.out.println("The middle word is " ); // Outputs the middle word in alphabetical order.
}
}
Please help!
Try something like this:
String [] strings;
int i = 0;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
strings[i++] = input.next(); //Sets "str1" = to first word.
strings[i++] = input.next(); //Sets "str2" = to second word.
strings[i++] = input.next(); //Sets "str3" = to third word.
Arrays.sort(strings);
System.out.println("The middle word is " + strings[strings.length / 2]);
You can sort (compare) only two words at a time, yes, but that is the basis for the whole sorting algorithm. You'll need to loop through your array of words and compare each word with each other word.
String[2] words = new String[2];
words[0] = input.next();
words[1] = input.next();
words[2] = input.next();
String[2] sortedWords = new String[2];
for (String word: words){ // outer loop
for (String word: words){ // inner loop to compare each word with each other
// logic to do the comparisons and sorting goes here
}
}
System.out.println(sortedWords[1]);
Of course I've left out the fun part for you, but that should get you started.

Read data in line into string array?

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;
}

Need help splitting a string into two separate integers for processing

I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split

Categories

Resources