I want to take input as a single line with spaces then enter that data into the two dimensional array.
String[][] examples = new String[100][100];
for (int i = 0; i < 2; i++) {
System.out.println("enter line " + i);
String line = sc.next();
String[] linearr = line.split("\\s+");
for (int j = 0; j < 5; j++) {
examples[i][j] = linearr[j];
System.out.println(linearr[j]);
}
}
Only the linearr[0] gets value entered ...linearr[1] , linearr[2] , so on do not get values rather says index out of bounds.
sc.next() only returns the first word.
sc.nextLine() returns the whole line.
And instead of
for(int j=0;j<5;j++)
{
examples[i][j]=linearr[j];
System.out.println(linearr[j]);
}
you can just do
examples[i] = linearr;
Instead of the sc.next():
String line=sc.next();
You should use:
String line=sc.nextLine();
Because next() can read input only till space and should be used for only single word.And if you are about to read a line you should use nextLine()
To know more read this
You wanted to receive a line, but your current code only receive a word per input.
Instead of using:
String line=sc.next(); //receive a word
Change it to:
String line=sc.nextLine(); //receive a line
so on dont get values rather says index out of bounds.....
Instead of using 5, the number of String tokens from the split can be used as the loop control for your inner loop, so you may want:
for(int j=0; j < linearr.length; j++)
This will prevent IndexOutOfBoundsException when there are lesser than 5 words in the input.
Related
I was writing a code for taking multple strings as input and storing them in an Array like below:
int NumberOfTC=scanner.nextInt();
String[] words=new String[NumberOfTC];
for(int i=0;i<NumberOfTC;i++){
words[i]=sc.nextLine();
System.out.println(words[i]);
}
But this allows a single input string
After much inspection i see that the below code works:
System.out.print("No of Strings to Enter: ");
int num = scanner.nextInt();
scanner.nextLine();
String[] words = new String[num];
for (int i = 0; i < num; i++) {
System.out.print("Enter a String: ");
words[i] = scanner.nextLine();
}
I am not able to decode what is the use of scanner.nextLine() after the scanner.nextInt() line. I mean why my earlier code is not working and prints only a single string whereas the second code works properly
I am making a search engine to find what document matches the words given by the user. The following is my code:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
stringArray[i] = userInput.next();
i++;
}
for (int j = 0; j < i; j++){
System.out.println(stringArray[j]);
}
This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.
hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
while (i < stringArray.length
&& userInput.hasNextLine()
&& !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
i++;
}
for (int j = 0; j < i; j++) { // just for testing purposes
System.out.println(stringArray[j]);
}
But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for:");
List<String> stringList = new ArrayList<>();
String line;
while (userInput.hasNextLine()
&& !(line = userInput.nextLine().trim()).isEmpty()) {
stringList.add(line);
}
stringList.forEach(System.out::println); // just for testing purposes
Change your while loop to this:
while (!(String temp = userInput.nextLine()).trim().contentEquals("")) {
stringArray[i] = userInput.next();
i++;
}
String line;
int i = 0;
while(!(line = userInput.nextLine()).isEmpty()) {
for (String word :line.split("\\s+")){
stringArray[i]=word;
i++;
}
}
This code assigns every line from Scanner into variable line until is not user input empty. In every iteration it splits line to words and assigns to stringArray.
I don't really get the behaviour of the Scanner. I want to input a single int first and in the while-loop, as you can see, next line inputs. But after the first input I get an ArrayOutOfBoundsException as you can see below. It just ignores that I want to input next lines. The only solution is when I input the int and the new line separated with a space in one line, but that isn't what I want, because at this point, the user doesn't know, what to input after the first int.
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt() - 1;
logic.setGameField(games.get(i).getGameField());
// scanner.reset(); //what does that do?
view.displayField(logic.getCompleteGameField(), logic.getGameSize(), logic.getCompleteGameSize());
double time = System.currentTimeMillis();
while (!logic.gameIsFinished()) {
System.out.println("Spalte Reihe Zeichen: X/*");
String s = scanner.nextLine();
char[] tmp = s.toCharArray();
//just for testing
System.out.println(s.length()); //outputs: 0
System.out.println(tmp.length); //outputs: 0
for (int j = 0; j < tmp.length; j++) {
System.out.print(tmp[j] + " " + j);
}
System.out.println();
logic.setSingleField(tmp[1] - CHAR_TO_INT_OFFSET_ROW, tmp[0] - CHAR_TO_INT_OFFSET_COLUMN, tmp[2]); //throws as expected ArrayIndexOutOfBoundsException
This is because Scanner.nextInt() doesn't bring you to the next line. At this point, you are still in current line of input. What you can do is call an additional Scanner.nextLine() after Scanner.nextInt():
int i = scanner.nextInt() - 1;
scanner.nextLine();
logic.setGameField(games.get(i).getGameField());
In this code I can get upto only 2 values instead of 3 input values. Why does it so? Please explain me.
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
nextInt will get the integer from the input buffer and will leave the new line character in the buffer. So when you call nextLine after that, the new line character in the buffer will be returned. To fix this, add a nextLine after calling nextInt
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
input.nextLine();//get the new line character and ignore it
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
See the answer from this link , it explains in detail what you are experiencing: Using scanner.nextLine()
In short the first nextLine reads the rest of the line from your nextInt call.
Use input.nextInt() instead of input.nextLine().
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
next() reads the input only till the space. It doesnt read the space between words.
First off i am pretty fresh when it comes to java. My program is supposed to ask the user for strings and print what they just put in. It is then supposed to change all characters to lowercase and remove all spaces from the strings and print this. After this, it is supposed to print a character array of the alphabet and use an asterisk (*) to show each time a character occurs in the string (I dont even know where to start here). Right now it just prints the String in an array(not correct). This is what I have so far. It will print either the string with no spaces or the original but not both. My object/array naming is atrocious and i apologize in advance. Any guidance would be greatly appreciated
EDIT: here is the question
In this assignment you are to write a program that will do the following:
Ask the user to input a positive integer m, and then read that integer. Use a
Scanner object declared in main to read this integer.
Call a method that will ask the user to input m strings. As the strings are
read, they should be concatenated into a single string st. After reading the m strings and forming the single string st, the method should return st. NOTE: This method will have two parameters, an int to receive m and a Scanner object to receive the Scanner object declared in main.
In main print the concatenated string received from the method.
In main convert the String object to lower case.
In main convert the lower case String object to an array of char. (All letters
will be lower case.)
In main print the character array just created. (Requires a looping structure.)
Call a method that will compress the character array in the following way.
The method will count the letters of the alphabet in the array, create a new array whose size is equal to that count, and copy only the letters of the original array into the new array. Return the new array.
In main declare an integer array of size 26. Call a method with two parameters, a character array x (which will contain only lower case letters, and an integer array z that will receive the one declared in main). The method will set all entries in the integer array to zero. It will then process through the lower case letter array and count the number of times each letter occurs. HINT: z[x[i]-97]++ can do the counting. The ASCII code for a is 97, so if x[i] is ‘a’, then z[0] will be incremented. ‘b’ would cause z[1] to be incremented, etc. The integer array now contains a frequency distribution for the letters in the array of lowercase letters.
Call a method with one integer array parameter (which will receive the frequency distribution array) and print each letter on a new line followed by the number of stars equal to the integer value in that array element. This must be neatly aligned. Hint: if i is an index with 0 ≤ 𝑖 ≤ 25, then (char)(i+97) is a lower case letter of the alphabet.
package lab6;
import java.util.Scanner;
public class Lab6 {
public char sent[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of strings you want: ");
int m = input.nextInt();
Lab6 loo = new Lab6();
loo.print(loo.loop(m));
}
public String loop(int m) { //print the string that was entered
String total = " ";
for (int i = 1; i <= m; i++) {
Scanner input = new Scanner(System.in);
System.out.println("enter string: " + i);
String st = input.nextLine();
total += st + "";
}
System.out.println(total);
return total;
}
public void print(String ht) { //print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
for (int i = 0; i < sent.length; i++) {
System.out.println(sent[i]);
}
}
}
Sounds like computer science is not your cup of tea. I Strongly recommend you refactor this code and try to figure out why it does what it does.
public void print(String ht) { // print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
int[] alphabet = new int[26];
//set all values to 0
for(int i = 0 ; i < alphabet.length ; i++){
alphabet[i] = 0;
}
//Loop through all characters and increment corresponding value
for(int i = 0 ; i < sent.length ; i++){
alphabet[sent[i] - 97]++;
}
//Print character + asterisk for each time the character is used
for(int i = 0 ; i < alphabet.length ; i++){
System.out.print((char)(i + 97) + ": ");
for(int nChars = 0 ; nChars < alphabet[i] ; nChars++){
System.out.print("*");
}
System.out.println();
}
}