Convert array element to a string and print first character? - java

I need to create an array of strings from user input and print the first letter of each element. I'm aware that I need to convert the array to a string somehow, but unsure how to accomplish this. I was unsuccessful with Arrays.toString
Following is my code:
import java.util.Scanner;
import java.util.Arrays;
class Main{
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
System.out.println("How many names would you like to enter in this array?: ");
int numName = inp.nextInt();
String nameArray[] = new String[numName];
System.out.println("Enter the names: ");
for(int i = 0; i <= nameArray.length; i++){
nameArray[i] = inp.nextLine();
}
System.out.println(nameArray.charAt(0));
}
}

You need to iterate over every String in the Array and then print the first char. You can do this using charAt() and a loop.
for(String str : nameArray) {
System.out.println(str.charAt(0));
}
Or you can use Arrays.stream():
Arrays.stream(nameArray).forEach(e -> System.out.println(e.charAt(0)));
Also just a few problems with your code:
You are going to enter into this problem, because nextInt() does not consume the newline. Add a blank nextLine() call after nextInt()
You are looping until <= array.length which will cause an indexOutOfBounds error. You need to only loop until less than array.length

Just do another iteration over the "nameArray", and get the first character of each array element, and print it.
For example, you can use for-each:
for(String name : nameArray) {
System.out.println(name.charAt(0));
}

Arrays.stream(nameArray).map(s -> s.charAt(0)).forEach(System.out::println);

Related

I have specified the size of the array using user input but my for loop is taking input only size-1 time

I have specified the size of the array using user input but my for loop is taking input only size-1 time.
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time=sc.nextInt();
String input[]=new String[time];
for(int i=0;i<time;i++)
{
input[i]=sc.nextLine();
}
for(int i=0;i<time;i++)
{
int len=input[i].length();
if(len>4)
{
System.out.println(input[i].charAt(0)+ Integer.toString(len-2)+input[i].charAt(len-1));
}
else
System.out.println(input[i]);
}
}
}
i changed my code and it is working fine
changed
int time=sc.nextInt();
with
int time=Integer.parseInt(sc.nextLine());
but i don't know the reason behind this . Please can anyone explain me
The Scanner.nextInt() method scans the next token of the input as an int, not the line. For example, if you give an int input and then hit enter, then it takes only the int, not the carriage return.
If you give a sample input like this:
2 xyz //hit enter and give the next input
abc
You'll see the nextInt() will take the 2 as input from that line and the upcoming first iteration for Scanner.nextLine() will consider the xyz as first input and in the next iteration, as we gave abc, it will be considered as the second. All these time you're code was working, but you couldn't see as it was taking the empty string as the first input due to the carriage return from the previous line.
However, The Scanner.nextLine() takes the whole line as input, along with the carriage return and then parses the int to the integer, so, you get the next lines for the string input for your array.
Hope that makes everything clear.
The problem is with the nextLine() method used in the first for loop. Because the method advances the scanner to the next line and returns the input that was skipped, it kind of "eats" one of your loop iterations and it ends up allowing you to input time - 1 elements into the array instead of time amount of elements. If you just use sc.next() instead, the program works perfectly fine, so you don't need to use
int time=Integer.parseInt(sc.nextLine());
as it may be a bit more complicated (in my opinion) than just replacing nextLine() with next(). Here is the code:
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time = sc.nextInt();
String input[] = new String[time];
for(int i = 0;i < time;i++)
{
input[i] = sc.next();
}
for(int i = 0;i < time;i++)
{
int len = input[i].length();
if(len > 4)
{
System.out.println(input[i].charAt(0) + Integer.toString(len - 2) + input[i].charAt(len - 1));
}
else
System.out.println(input[i]);
}
sc.close();
}
}

For loop skipping index 0 when user's input and print in Java

For example, I entered a size of 3 Students. It skips index 0 in the console also in printing.
Please refer to this image, I have a sample size of 3 students and its output.
I don't have the slightest idea of why it skips index 0? Thanks for the help!
import java.util.Arrays;
import java.util.Scanner;
class string{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
}
The problem is with the console.nextInt(), this function only reads the int value.So In your code inside the loop console.nextLine() first time skip the getting input.just puting console.nextLine()afterconsole.nextInt()
you can solve the problem.
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
console.nextLine();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
The reason for this skip is due to the different behavior of the console.nextInt() and console.nextLine() as:
console.nextInt() reads the integer value entered, regardless of whether you hit the enter for new-line or not.
console.nextLine() reads the whole line, but as you previously hit thee enter when you give the size of Array.
3 was accepted as the size of the Array and when you hit enter it was accepted as the first value for you array which is a blank space or I can say it is referred as "".
Following are the two resolution for this:
Either put a console.nextLine() call after each console.nextInt() to consume rest of that line including newline
Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. you may convert to an integer using int studentSize = Integer.parseInt(console.nextLine()) method. (Surround it with try-catch)

Skipping whitespace when adding chars to a list

I am trying to take a user entered word or phrase and put the characters in alphabetical order by putting them in a list and sorting the list. Here is my code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SortAlphabetically {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Character> alpha = new ArrayList<Character>();
System.out.println("Enter a word or phrase");
StringBuilder input = new StringBuilder(scanner.next());
scanner.close();
for (int i = 0; i < input.length(); i++) {
if (Character.isWhitespace(input.charAt(i))) {
input.deleteCharAt(i);
} else {
alpha.add(input.charAt(i));
}
}
alpha.sort(null);
System.out.println("Input sorted alphabetically: " + alpha);
}
}
However, the input seems to stop being entered into the list after a white space character. For example:
Enter a word or phrase
cba fed
Input sorted alphabetically: [a, b, c]
I tried to fix this with
if (Character.isWhitespace(input.charAt(i))) {
input.deleteCharAt(i);
}
but it doesn't seem to have done anything
scanner.next() reads a single token, so it stops at the first white space.
If you use scanner.nextLine(), it will read the entire line, including the space.
You have to use the scanner.nextLine() to get the entire line with all the white-spaces. In addition, you have a better way to implement the solution in just one line using simple java library functions in java.lang.String. Why waste lines!
System.out.println("Answer"+input.replaceAll( " ", "" ).toCharArray().toList().sort());

How to match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

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