For loop: populate array from user input [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was setting up a small app that asks a user to determine the array size and then populate it. The used "for" loop skips the index 0; but I'm uncertain why.
If you run this code with 1 as the array size it skips over the user inputting the first word.
The issue is certainly on the for-loop but it is so simple that I don't see it.
Thanks!
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int arrayDimesion;
Scanner sc = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
arrayDimesion = sc.nextInt();
String[] wordArray = new String[arrayDimesion];
//Populate with user input
for (int i=0; i<arrayDimesion; i++) {
System.out.println("Please enter a word");
wordArray[i] = sc.nextLine();
}
//Print all entered Strings
System.out.println("This are the words you entered: ");
for(int i = 0; i < wordArray.length; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
int r = (int)(Math.random() * wordArray.length);
System.out.println("The random word is: " + wordArray[r]);
}
}

Change your
arrayDimesion = sc.nextInt();
to
arrayDimesion = Integer.parseInt(sc.nextLine());
Reason: sc.nextInt() doesn't consume the newline character that you give after taking arrayDimesion input. This later on gets consumed in the next sc.nextLine() call.
PS: It might throw NumberFormatException. So you can handle it like :
try {
arrayDimesion = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}

The below code is clean, easy to read and handles the edge cases.
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int numOfWords;
Scanner scanner = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
numOfWords = Integer.parseInt(scanner.nextLine());
String[] wordArray = new String[numOfWords];
//Populate with user input
System.out.println("Please enter the word(s)");
for (int i = 0; i < numOfWords; i++) {
wordArray[i] = scanner.nextLine();
}
//Print all entered Strings
System.out.println("These are the words you entered: ");
for (int i = 0; i < numOfWords; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
if (numOfWords == 0) {
System.out.println("You didn't enter a word");
} else {
int r = (int) (Math.random() * numOfWords);
System.out.println("The random word is: " + wordArray[r]);
}
}
}

Related

Java loop ignoring first input each loop

I am a beginner and have a simple piece of code that works - it is designed to ask a user for seven numbers and store them in an array then print out what they entered
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
What I want to do is add an error trap to make sure the number is not greater than 49 - I have added the following code and there are no errors and it runs fine but I have to add two numbers for each loop as it only stores the second input - can anyone help tell me why?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
if ( in .nextInt() > 49) {
System.out.println("please enter a number less than 49");
inputs[i] = in .nextInt();
} else
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
when you do in.nextInt() it give you the "next" integer in the input, so you are doing this twice for each loop cycle, once in the if statement and the other in the if or else body. so you need invoke that function only once. something like this:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] inputs = new int [7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++)
{
int current_input = in.nextInt()
if ( current_input > 49)
{
System.out.println("please enter a number less than 49");
inputs [i] = in.nextInt();
}
else
inputs [i] = current_input;
}
System.out.println("You have entered the numbers:");
for (int i : inputs)
{
System.out.println(i);
}
}
I don't test the code but you have the idea.
here you have another problem still, and is that when the user types a number over 49, the second time you ask the number to the user, you don't test again that it's below 49 so the user can enter any number.

Exiting a loop when there are no more inputs

I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....
import java.util.Scanner;
public class getArray{
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()){
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:
--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21
Enter nothing to end data entry and view array contents:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("Enter all the Integer values you would like");
System.out.println("stored into your int[] array. You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white");
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("Enter a numerical value: --> ");
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the 'data entry' loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
If I understand correctly, then you want the input of numbers to be limited to the size of the array?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
A solution using Java Stream API:
Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");
int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
.limit(20) // take only 20 values from stream
.toArray(); // put them into array
System.out.println(Arrays.toString(arr)); // print array contents at once
Also, there's a utility method Arrays.setAll allowing to set array values via IntUnaryOperator:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}

How to make the program to check the instance of a letter in java?

I am creating a cash register where I have to use a scanner and can only have 5 input amounts. It has to also include hst and that is by only having a "h" after or before an amount. My question is how would the program recognize that I have put an "h" after or before an amount? This seems to be done only using a string variable, so how would I accomplish that? I have to store the inputs in an array, and so I got that to work.
My Code:
// Import scanner class
import java.util.Scanner;
// Create class and method
class Main {
public static void main(String[] args) {
// Declare the scanner object and create scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");
// Define an array double variable, set the limit to 5 inputs
double[] numbers = new double[5];
// Create a for loop to input any numbers 5 times
for (int i = 0; i < numbers.length; i++){
// Add a scanner input to let the user type out the values
numbers[i] = inp.nextDouble();
}
}
}
below code asks the user input for 5 times , and only valid values will be in the Array , Vald values are the values with 'h' at start or end and should only occur once. i.e. at 'h' at both end and start or more than once is invalid.
public static void main(String[] args) throws ParseException {
int counter = 1;
Double[] result = new Double[5];
int index = 0;
while(counter <= 5) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an Amount ");
String value = scanner.nextLine();
int indexOfH = value.indexOf("h");
int lastIndexOfH = value.lastIndexOf("h");
boolean containsHatstartsOrEnd = indexOfH == 0 || indexOfH == (value.length()-1);
if(containsHatstartsOrEnd && indexOfH==lastIndexOfH){ //Validate h at begins or end and should contains only once
result[index] = Double.parseDouble(value.replace("h", ""));
index++;
}
counter++;
}
System.out.println("Printing Valid values");
for(int i=0; i< result.length; i++) {
if(result[i]!=null) {
System.out.println(result[i]);
}
}
}
input & result
Enter an Amount 13.45h
Enter an Amount 55h.65
Enter an Amount 32h.33h
Enter an Amount h100.23
Enter an Amount h20
Printing Valid values
13.45
100.23
20.0

user input to a Char Array

I am trying to create a program that takes a user's answer for a test and puts it in a char array, and then compares it to an array with the answers.
I have a problem with input the user's Answers into the char array. I keep getting an EE saying that in.nextLine(); - there is no line found and it throws a no such element exception.
import java.util.Scanner;
public class driverExam {
public static void main(String[] args) {
System.out.println("Driver's Test. Input your answers for the following
10 Q's. ");
System.out.println();
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =9;
String userInput;
for (int i =0; i<uA;i++) {
Scanner in = new Scanner(System.in);
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();
int len = userInput.length();
char[] userAnswers = new char [len];
for(int x =0;x<len;x++) {
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
System.out.println(userAnswers);
}
System.out.println("Your answers have been recorded.");
System.out.println();
}
}
Shouldn't userAnswers array be of size 10?
Your program has quite redundant and unnecessary steps, according to me. So I have modified it to meet your need.
There is no need to put the "Scanner in...." inside the loop.
This loop is full of mistakes. Not discouraging, just saying.
for (int i =0; i<uA;i++)
{
Scanner in = new Scanner(System.in);//scanner inside loop
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();//already mentioned by someone in the comment
int len = userInput.length();
char[] userAnswers = new char [len];//no need to declare array inside loop
for(int x =0;x<len;x++)
{
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
}
System.out.println(userAnswers);//this will not print the array,it will print
//something like [I#8428 ,[ denotes 1D array,I integer,and the rest of it has
//some meaning too
Now here is the code which will get the work done
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =testAnswers.length;//to find the length of testAnswers array i.e. 10
char[] userAnswers = new char [uA];
char userInput;
int i;
Scanner in = new Scanner(System.in);
for (i =0; i<uA;i++)
{
System.out.print("Question #"+(i+1)+": ");
userInput = Character.toUpperCase(in.next().charAt(0));
}
for(i=0;i<ua;i++)
{
System.out.println(userAnswers[i]);
}
System.out.println("Data has been recorded");
I am not demeaning, just trying to help.

Java - Scanner does not remove all of the desired objects

I am trying to make some kind of 'Evil Hangman game' (nifty Stanford CS exercises). The purpose of the game is to 'cheat' by removing as many possible word solutions as possible so the user cannot guess before the very end.
I have made a loop (below) which seems to remove many of the words possible words but for some reason it does not remove all of them. The input is a dictionary.txt file which contains about 120K words.
When I 'guess' the letter "a" it will take away roughly 60-70% of the words with "a" in them (estimate based on comparisons between the output with the first couple of words in the txt file)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
I am aware that my code is a bit messy at this point, I am trying to improve everything about my programming so all feedback is greatly appreciated! I have the feeling that I am including stuff that does not have to be there and so on.
I will post the whole code below in case that helps:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// introduction and prompting the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while ( textScan.hasNext() )
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Finally figured out it had to do with the scanner. It had to be initiated inside the loop
for(int i = 1; i <= guessNumber; i++)
{
Scanner textScan2 = new Scanner(file1);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
//System.out.print(guess);
while ( textScan2.hasNext() )
{
String word1 = textScan2.next();
if (wordLength != word1.length() || (word1.contains(guess)))
{
wordList.remove(word1);
}
}
}

Categories