User input string into string array [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get the user's input, then store the input into an array. I'm going to get a string input and with this code, I thought it would work, but it's not working. Any help would be appreciated!
import java.util.Scanner;
public class NameSorting {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
Scanner s1 = new Scanner(System.in);
for (int i = 0; i < 0;){
array[i] = s1.nextLine();
}
//Just to test
System.out.println(array[0]);
}
}

Since you know that you want to have an array of 20 string:
String[] array = new String[20];
Then your for loop should use the length of the array to determine when the loop should stop. Also you loop is missing an incrementer.
Try the following code to get you going:
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
}
//Just to test
System.out.println(array[0]);
}

Look at your for-loop, it lacks of increment attribute. Example: for(int i = 0; i < 0; i++)
If you want to debug each loop I recommend you to print assignment inside for-loop
for (int i = 0; i < 0;)
{
array[i] = s.nextLine();
System.out.println(array[i]); // Debug
}

for (int i = 0; i < 0;){
array[i] = s.nextLine();
}
For the first iteration i will be initialised to '0' and since i should be less then '0' as per your condition it wont even go into the loop.change the loop to
for(int i=0;i<20;i++){
array[i]=s.nextLine();
}

Related

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.

Trying to sort user input into alphabetical order with Java, why won't this code work?

For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.
You probably want to use set instead.
You may need to change the loop condition to
s1.hasNextLine() && !input.equals("done")

Creating a random output from an user input array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

Why is this simple program not working

So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}

System.in.read() does not block to read more input characters? [duplicate]

This question already has answers here:
for loop in Java runs 3 times before taking next input
(2 answers)
Closed 8 years ago.
Can anyone please explain why the following code behaving strangely:
public class UserInputTest {
public static void main(String[] args) throws IOException {
int n=3;
char[] arr = new char[n];
for (int i=0; i<n; i++) {
System.out.println(i+1 + " character :");
arr[i] = ((char)System.in.read());
}
System.out.println("You Entered : ");
for (int i=0; i<n; i++) {
System.out.println(arr[i]);
}
}
}
OUTPUT:
1 character :
u
2 character :
3 character :
You Entered :
u
I was expecting it to block three times for a user to input values.
Any comments ?
Thanks,
Mohit
Reading character from console has above mentioned enter issue. So, try to read as string:
public static void main(String args[]){
int n=3;
char[] arr = new char[n];
Scanner in = new Scanner(System.in);
for (int i=0; i<n; i++) {
System.out.println(i+1 + " character :");
String s1 = in.nextLine();
arr[i] = s1.charAt(0);
}
System.out.println("You Entered : ");
for (int i=0; i<n; i++) {
System.out.println(arr[i]);
}
}
You typed a character followed by the Enter key. The second read returns the Enter.
The right way to enter individual characters is to use a GUI such as a Swing GUI. You can't enter individual characters with the standard Java console.
You can use a non-standard console for this such as JCurses but not the standard Java console.

Categories