Java how to print arrays? [duplicate] - java

This question already has answers here:
Cannot invoke add on the array type
(2 answers)
Java increase array by X size
(6 answers)
Closed 2 years ago.
I'm kinda new to programming and I know that the problem is pretty simple.. but I couldn't figure it out..
Let's say that I'd like to create an arraylist like this ;
String words [ ] = { } ; instead of ArrayList words = new ArrayList(); or
ArrayList<String> words= new ArrayList<String>();
but the problem is... when I want to add the words that we scan on the string that we created to the list , I get an error..
("Cannot invoke add(String) on the array type String[]
") I've tried to use Arrays.toString() method.. but I guess there is
something that I miss.. Could you guys help me out?
import java.util.Arrays;
import java.util.Scanner;
public class testing_Stuff {
public static void main(String[] args) {
String sentence =("This is texting");
Scanner scan = new Scanner(sentence);
String words [] = {};
while(scan.hasNext()) {
words.add((scan.next());
}
System.out.println(words);
}
}

You are trying to use the add method on an array which is not possible. Also, you have some syntax mistakes.
You can either define a length to the array from the start and add to it as follows:
String sentence ="This is texting";
Scanner scan = new Scanner(sentence);
String words[] = new String[sentence.split(" ").length];
int i = 0;
while(scan.hasNext()) {
words[i++] = scan.next();
}
System.out.println(Arrays.toString(words));
Or you can use a list as follows:
String sentence = "This is texting";
Scanner scan = new Scanner(sentence);
List<String> words = new ArrayList<>();
while(scan.hasNext()) {
words.add(scan.next());
}
System.out.println(words);
In both cases the output would be:
[This, is, texting]

Related

Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Main.main(Main.java:16) [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
i'm beginner Java. My code is to convert Morse code entered from the keyboard and output as meaningful characters. This is just a 3-letter "A" "B" "C" test but when I ran it had an error.
Help me, please !
import java.util.*;
import java.io.*;
public class Main {
public static void main (String[] args) {
String [][] Morse = new String[60][2];
Morse[0][0] = "A" ; Morse[0][1] = ".-" ;
Morse[1][0] = "B" ; Morse[1][1] = "-...";
Morse[2][0] = "C" ; Morse[2][1] = "-.-.";
Scanner ip = new Scanner(System.in);
String s = ip.nextLine();
String [] op = s.split(" ");
for (int i = 0 ; i < 60 ; i++)
if ( op[i] == Morse[i][1] ) System.out.print(" "+Morse[i][0]);
}
}
Welcome to stack overflow, please go though the How To Ask A Question before you make post.
I will list some problems and their causes as you are getting started with Java.
Here is a helpful link with some Data Structures to approach an Object Oriented use case scenario.
Regarding your code
First of all take a look at How To Split A String In Java
For Input: "A"
String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] is null because there is no space to split it with
For Input: "A (1 space)"
String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] No "Space" to add to op[1]
For Input: "A (1+ spaces)"
String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] Still no "Space" to add to op[1]
Solution:
Change if ( op[i] == Morse[i][1] ) to if ( op[0] == Morse[i][1] )
Remember the input is always at the 0 index of the op Array
For me, it doesn't trigger an ArrayOutOfBoundsException you can continue with implementing your logic in your case senario.
You can use a data structure called HashMap, check the following code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Sol {
public static void main(String[] args) {
Map<String, String> morseToText = new HashMap<>();
morseToText.put(".-", "A");
morseToText.put("-...", "B");
morseToText.put("-.-.", "C");
Scanner ip = new Scanner(System.in);
String s = ip.nextLine();
String[] op = s.split(" ");
for (String s1 : op) {
System.out.print(morseToText.get(s1));
}
}
}

How to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

Where is the empty line coming from? How to remove it? - Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I would like to print out strings without duplicated words. The first int determines how many Strings I have, followed by the strings with duplications. But in my output I get an empty line at the first line and I would like to know how to get rid of this first empty line?
Thank you for your time and help!
Input Example:
3
Goodbye bye bye world world world
Sam went went to to to his business
Reya is is the the best player in eye eye game
Output:
*empty line*
Goodbye bye world
Sam went to his business
Reya is the best player in eye game
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lines= sc.nextInt()+1;
String [] str= new String[lines];
for(int i=0;i<lines;i++) {
str[i]=sc.nextLine();
}
for(int i=0;i<lines;i++) {
String temp= str[i];
String[] strWords = temp.split("\\s+");
LinkedHashSet<String> hstr = new LinkedHashSet<String> ();
for(int j=0;j<strWords.length;j++) {
hstr.add(strWords[j]);
}
String[] strArr = new String[hstr.size()];
hstr.toArray(strArr);
for(int k=0;k<hstr.size();k++) {
System.out.printf("%s", strArr[k] + " ");
}
System.out.println();
}
sc.close();
}
When you type 3 for lines, this code:
int lines= sc.nextInt()+1; // why + 1?
String [] str= new String[lines];
for(int i=0;i<lines;i++) {
str[i]=sc.nextLine();
}
creates an array of 4 elements with the 1st being an empty string ""

Java Iterate through a string and pull out sections to add to an ArrayList [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I have a text file that contains names followed by .xml such as georgeeliot.xml I then took the text file and placed it into a string. I am now trying to figure out how to loop through the string and place each name.xml into a ArrayList that I created ArrayList<String> items = new ArrayList<String>();
I've done some research, but most examples I can find put them into an array. Thanks for your help.
`
You don't share what your delimiter is, but something like this will work:
final String DELIMITER = " "; // using space
String example = "one.xml two.xml three.xml";
List<String> items = Arrays.asList(example.split(DELIMITER));
for (String item : items) { // test output
System.out.println(item);
}
You'd probably be best just adding it to the List when you read the file unless you need the String representing the file contents for some other purpose. For example using Scanner:
Scanner sc = new Scanner(new File("file.txt")); // default delimiter is whitespace
/**
* or if using a custom delimiter:
* final String DELIMITER = " "; // using space
* Scanner sc = new Scanner("file.txt").useDelimiter(DELIMITER);
*/
List<String> items = new ArrayList<>();
while (sc.hasNext()) {
items.add(sc.next());
}
for (String item : items) { // test output
System.out.println(item);
}
file.txt
one.xml
two.xml
three.xml

Comma-Delimited String of Integers

This is the original prompt:
I need to write a program that gets a comma-delimited String of integers (e.g. “4,8,16,32,…”) from the user at the command line and then converts the String to an ArrayList of Integers (using the wrapper class) with each element containing one of the input integers in sequence. Finally, use a for loop to output the integers to the command line, each on a separate line.
This is the code that I have so far:
import java.util.Scanner;
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> myInts = new ArrayList<String>();
String integers = "";
System.out.print("Enter a list of delimited integers: ");
integers = scnr.nextLine();
for (int i = 0; i < myInts.size(); i++) {
integers = myInts.get(i);
myInts.add(integers);
System.out.println(myInts);
}
System.out.println(integers);
}
}
I am confused on where to go with the rest of this program. If someone could help explain to me what I need to do, that would be much appreciated!
As Matthew and Marc pointed out you have to first split the string into tokens and then parse each token to transform them into Integers.
You could try it with something like this:
String stringOfInts = "1,2,3,4,5";
List<Integer> integers = new ArrayList<>();
String[] splittedStringOfInts = stringOfInts.split(",");
for(String strInt : splittedStringOfInts) {
integers.add(Integer.parseInt(strInt));
}
// do something with integers
In the split() method you define how to split the string into tokens. In your case it's simply the comma (,) sign.
Hope this helps.
Regards Patrick

Categories