I'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).
So I decided to use a while loop to use Scanner n times, so that each time the user could store an String in that location as the loop advances.
But when I run the code, it just prints the statements don't letting me (or the user) to input the String.
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main, I tried using Thread.sleep(4000); but the output is an error Unhandled exception type InterruptedException.
The problem is that you are not scanning inside the while loop. You need to scan the words the way you have scanned the integer. Instead of using d.next(), you've used d.toString().
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner. You do not need two instances of Scanner. You can reuse the same instance of Scanner everywhere in your program.
Related
I will keep this short and simple, here's the program-
class Sample{
private int n;
public void getDetails(){
Scanner y=new Scanner(System.in);
n=y.nextInt();
System.out.println("Entered 'n' = "+n);
}
public void displayDetails(){
int i,j;
int arr[]=new int[n];
Scanner x=new Scanner(System.in);
for(j=0;j<n;j++) {
arr[j] = x.nextInt();
System.out.println("Entered element = "+arr[j]);
}
System.out.println("Entered array: ");
for(i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getDetails();
obj.displayDetails();
}
}
This simple program just takes number of elements(n) and the elements of array(arr[]) as input in different methods.
When the input is given in interactive mode, everything works fine. Here's the console output-
5
Entered 'n' = 5
1 2 3 4 5
Entered element = 1
Entered element = 2
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
But when I give it as Stdin input(or all input at once), it just takes the number of elements(n) and ignores my array input(arr[]). Here I had to give the array elements again. Console output-
5
1 2 3 4 5Entered 'n' = 5
1
Entered element = 1
2
Entered element = 2
3 4 5
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
I have no idea what is happening. Is it a bug? Please help
Part of the problem is that you are creating multiple scanners. Create one scanner and use it everywhere, like so:
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getArraySize();
obj.displayDetails();
}
}
class Sample{
private int arraySize;
Scanner scanner = new Scanner(System.in);
public void getArraySize(){
System.out.print("Enter size of array: ");
arraySize = scanner.nextInt();
System.out.println("Entered array size = " + arraySize);
}
public void displayDetails(){
//Create an integer array of size arraySize
int intArray[] = new int[arraySize];
//Repeatedly request integers for the array
for( int i=0; i<arraySize; i++) {
int nextInt = scanner.nextInt();
intArray[i] = nextInt;
System.out.println("Entered element = " + intArray[i]);
}
//Print out the entered elements
System.out.println("Entered array: ");
for( int i=0; i<arraySize; i++) {
System.out.print(intArray[i]+" ");
}
scanner.close();
}
}
console output:
Enter size of array: 5
Entered array size = 5
5 4 3 2 1
Entered element = 5
Entered element = 4
Entered element = 3
Entered element = 2
Entered element = 1
Entered array:
5 4 3 2 1
You still need to check that the next value is actually an int. If you put a different type of value in there, like a letter, it will crash. See these links for additional details:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Java Multiple Scanners
Why is not possible to reopen a closed (standard) stream?
You areusing scanner to take userinput.
Scanner y=new Scanner(System.in);
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for Scanner class, due to nextXXX() methods ignore newline character and nextLine() only reads newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character.
Please check this SO link it has good explaination.
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
So when I run my program's main method it prints:
Enter number of test cases:
1
Enter string 1
Enter string 2
rat apple cat ear cat apple rat
For some reason it prints Enter string 1 and Enter string 2 before I even put in anything for String one. Can anyone shed any light as to why this is happening. Is there something wrong with the way I have the BufferReader setup?
Code:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int testcases = in.read();
System.out.println("Enter string 1");
String[] str1 = in.readLine().split(" ");
System.out.println("\nEnter string 2");
String[] str2 = in.readLine().split(" ");
for(int i = 0; i < testcases; i++)
{
String result = lcss(str1, str2);
System.out.println("\nLCSS: "+ result);
System.out.println("\nLCSS Length = "+ result.length());
}
}
Please use the following.
int testcases = Integer.valueOf(in.readLine());
Read more on BufferedReader.read()
int testcases = in.read(); doesn't read the line break (when you press Enter).
The readLine() in the line String[] str1 = in.readLine().split(" "); will now begin to read directly after the number you entered and search for the next line break. The line break from you entering the number is now found and the function directly returns without waiting for your input.
So much for the explanation on what causes your program to behave the way it does.
Now you do have another error, as BufferedReader.read() doesn't do what you think it does. Check the documentation
So when you enter a 1 your testcases varaible will contain the UTF-16 value of the character '1' which is 31.
As other answers already pointed out you should either use Integer.valueOf(in.readLine()); to get the value for testcases or use Scanner
EDIT:
Get the number of test cases as integer
Create a 2 dimensional array to store test cases. First dimension holds each test case & second dimension holds String[] of word list in each test case.
Iterate through "for loop" until you get each test case string array for total number of test cases,
Sample code:
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int testcases = in.nextInt();
System.out.println("test cases:"+testcases);
String[][] strs = new String[testcases][];
for ( int i =0; i< testcases ; i++ ){
System.out.println("Enter string:"+i);
in = new Scanner(System.in);
if (in.hasNext()) {
String s = in.nextLine();
System.out.println(s);
strs[i] = s.split(" ");
System.out.println("Length:"+strs[i].length);
}
System.out.println();
}
// Add your logic
}
Problem
I want to be able to ask the user to enter a word, then loop through an array that contains words, and search whether that word is in the array.
If the word is not in the array, then it will continue to ask the user for a word until that word is found in the array.
If the word is found in the array, then it will print it out and do something with that word. Loop ends.
Note:
I do not want to use a flag variable. Instead, I want to use only a loop to go through each value in the array and compare it with each new word entered by the user then stop upon the word matching in the array. This method should not use any flag values that stops when changing from false to true, and vice verca.
Program.Java
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userInput;
String array[] = {"Hello", "World"};
System.out.print("Enter word: ");
userInput = input.next();
for(String i : array)
while(!choice.equals(i)) {
System.out.print("Input not found in array. Enter new value: ");
userInput = input.next();
}
System.out.println("Word found in array.");
}
Unintended Output
Instead of stopping when the value in the array is found, it continues to ask for another input, and never terminates.
Example
Enter word: month
Input not found in array. Enter new value: Hello
Input not found in array. Enter new value: World
[...]
Input not found in array. Enter new value:
Intended Output:
Enter word: month
Input not found in array. Enter new value: Hello
Word found in array.
How I want to implement it
To loop through all the values in the array. Compare user input with each value in the array. If the user input matches none of the values in the array, then continue to ask for a new word, until that word matches the value in the array.
Separate the process of finding the value from the process of asking for a value. This is two distinct operations:
Ask for a string
Given a string, search for it in your array (a proper array, declared as String[])
Here's a hint. I'd recommend breaking those things out.
public boolean findWord(String candidateWord) {
for(String word : string) {
if(word.equals(candidateWord)) {
return true;
}
}
return false;
}
public void askForWords() {
System.out.println("Find a word! ");
Scanner scan = new Scanner(System.in);
String candidateWord;
boolean found = false;
do {
System.out.print("What word do you want to find? ");
found = findWord(scan.nextLine());
if(!found) {
System.out.println("Can't find that - try again?");
System.out.print("What word do you want to find? ");
scan.nextLine();
}
} while(!found);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userInput;
String array[] = {"Hello", "World"};
System.out.print("Enter word: ");
userInput = input.next();
while (true) {
for(String i : array) {
if(userInput.equals(i)) {
System.out.println("Word found in array.");
return;
}
}
System.out.print("Input not found in array. Enter new value: ");
userInput = input.next();
}
}
Note the placement of while and for and the return statement
This code below should work perfectly fine for you. Your for loop actually checks a string both the times even if it is matched at the first attempt. Therefore, it is solved below by adding a boolean check and break at some attempts where the input string is matched. There were some syntax problems in your code which I solved as below:
import java.util.*;
import java.io.*;
public class abcd {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userInput = "";
String[] array = {"Hello", "World"};
boolean check = true;
System.out.print("Enter word: ");
userInput = input.next();
while(true) {
for(String i : array) {
if(userInput.equals(i)) {
System.out.println("Word found in array.");
check = false;
break;
}
}
if(check) {
System.out.print("Input not found in array. Enter new value: ");
userInput = input.next();
continue;
}
break;
}
}
}
I am very new to java. I am trying to prompt the user to enter 4 integer numbers followed by a space and eventually print them out at the end. I am a little confused with the order of how I write things out and using the split(" ");
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
int numbers = keyboard.nextInt();
// Need split(" "); here?
} // End main string args here
} // End class calculations here
Any help or advice is appreciated. I have looked at other ways on stackoverflow but somehow I keep getting errors.
Read it in one String with keyboard.nextLine
Use the split method of String for get an array of Strings
Convert every element of the array to int with Integer.parseInt
Print your ints.
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
// Scan an entire line (containg 4 integers separated by spaces):
String lineWithNumbers = Keyboard.nextLine();
// Split the String by the spaces so that you get an array of size 4 with
// the numbers (in a String).
String[] numbers = lineWithNumbers.split(" ");
// For each String in the array, print them to the screen.
for(String numberString : numbers) {
System.out.println(numberString);
}
} // End main string args here
} // End class calculations here
This code will print all numbers, in case you actually want to do something with the Integers (for example mathematical operations) you can parse the String to an int, like so:
int myNumber = Integer.parseInt(numberString);
Hope this helps.
If would suggest to use the abilities of the Scanner class to retrieve numbers from the user input:
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[4];
System.out.println("Enter 4 integer numbers here: ");
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
numbers[i] = keyboard.nextInt();
}
System.out.println(Arrays.toString(numbers));
This code creates an array of size 4 and then loops over the user input reading the numbers from it. It will stop parsing the input if he has the four numbers, or if the user enters something different than a number. For example, if he enters 1 blub 3 4, then the array will be [1, 0, 0, 0].
This code has some advantages compared to the nextLine approaches of the over answers:
you don't have to care about the integer conversion (exception handling)
you can either write these number onto one line or each number on its own line
If you like to read an arbitrary amount of numbers, then use a List instead:
List<Integer> numbers = new ArrayList<>();
System.out.println("Enter some integer numbers here (enter something else than a number to stop): ");
while (keyboard.hasNextInt()) {
numbers.add(keyboard.nextInt());
}
System.out.println(numbers);