user input to a Char Array - java

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.

Related

Taking a user input string to form an array

I am trying to create an array that uses a user input string to form the base for the array. It's supposed to be an encryption program that takes the string the user enters and puts it in an array at the index 0, all the way down the column. For example, if I typed in car, the array would look like array[0][0] c, [1][0] a, [2][0] r. After the encryption, whatever car turns into would go into the second row, but for the life of me I can't even figure out how to create the first array.
So far my file looks like this:
public class Csci1301_hw3
{ //Start of class
public static void main(String[] args)
{ //Start of Main Method
String userinput;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a sentence you would like to encrypt.");
userinput = scan.nextLine();
char current;
int arraylength = userinput.length();
char[][] outputarray = new char [arraylength][];
for (int index=0; index < arraylength; index++);
{
if (current.charAt(0) < userinput.charAt(0))
current = userinput.charAt(0);
outputarray[0][0] = current;
current++;
}
String userinput;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a sentence you would like to encrypt.");
userinput = scan.nextLine();
char current;
int arraylength = userinput.length();
char[][] outputarray = new char [arraylength][];
for (int index=0; index < arraylength; index++);
{
if (current.charAt(0) < userinput.charAt(0))
current = userinput.charAt(0);
outputarray[0][0] = current;
current++;
}
This is my first coding class so I am very new to this, but even after rewatching lectures, reading my textbook, or even going over my professor's examples, I am unable to figure this out. The closest I got was it would just print out null for the entire array no matter what I typed.
I think there are a couple of things you might want to check, first your current variable,you should assign a value to it before using it in an if statement. second, I think you might want to consider using the index variable inside the if statement like:
userinput.charAt(index);
and in other places too. Because you want to go over all the chars in a string. the last thing I wasn't sure about is why incrementing the current variable?
update:
String userInput;
Scanner stdin = new Scanner(System.in);
System.out.println("Please enter a sentence you would like to encrypt.");
userInput = stdin.nextLine();
int arraylength = userInput.length();
char[][] outPutArray = new char [arraylength][2];
for (int i = 0; i < arraylength; i++)
{
outPutArray[i][1] = userInput.charAt(i);
}
for (int i = 0; i< outPutArray.length; i++)
System.out.print(outPutArray[i][1]);

Java program of returning alphabets that a word is made of

I am trying to understand how pieces of code are contributing the program in java. So the program is supposed to take input from user for a word and then the output is printing the alphabets that the user inputted word is made of. The program is running fine but I need help in interpreting what the for loops are doing. Thank you!
import java.util.Scanner;
public class J0307_search {
public static void main(String[] args) {
String str1;
int count;
char[] arr1=new char[40];
Scanner s=new Scanner (System.in);
System.out.print("input a string:");
str1=s.nextLine();
arr1[0]=str1.charAt(0);
System.out.print(arr1[0]+"");
for (int i=1; i<str1.length();i++) {
count=0;
for (int j=0;j<i;j++) {
if (str1.charAt(i)==str1.charAt(j)) {
count++;
}
}
if (count<1) {
arr1[i]=str1.charAt(i);
System.out.print(arr1[i]+"");
}
}
System.out.print(" : only made up of these alphabets");
s.close();
}
}
I change code and add explain.
boolean behindExist;
for (int i=1; i<str1.length(); i++) {//loop for all character in string
behindExist = false;
for (int j=0; j < i; j++) {
//check same character is exist before now char
//Ex) if (i = 3), check
//str1.charAt(3) == str1.charAt(0);
//str1.charAt(3) == str1.charAt(1);
//str1.charAt(3) == str1.charAt(2);
if (str1.charAt(i)==str1.charAt(j)) {
behindExist = true;
}
}
if (!behindExist) {//if not behindExist
arr1[i]=str1.charAt(i);//add to arr1
System.out.print(arr1[i]+"");//and print character
}
}
And, this is my code.
Scanner sc = new Scanner(System.in);
System.out.print("input a string : ");
String input = sc.nextLine();
for(int charCode : input.chars().distinct().toArray()) {
System.out.print((char)charCode);
}
System.out.print(" : only made up of these alphabets");
sc.close();
Short. I love it. I hope this can be help. :)
Can we use something as simple as this? The Set will contain unique characters that make up the word.
char[] charArr = str1.toCharArray();
Set<Character> charSet = new HashSet();
for(char c: charArr){
charSet.add(c);
}
Why to complex the problem.
Try to use features of collection in java.
something like this:-
Set<Character> set = new HashSet(Arrays.asList(str1.toCharArray()));

For loop: populate array from user input [duplicate]

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]);
}
}
}

How do input characters into an array through user input?

This is essentially what i have, everything works fine, but for some reason I'm not able to input the characters into the array.
If you could explain to me why it isn't working it would be greatly appreciated.
The purpose of this is to input a series of characters into an array, and to count the number of ' ' (gaps) present within it.
The part in bold is where I'm currently having my issue.
import java.util.*;
public class Test4c{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
Scanner a = new Scanner(System.in);
int size;
System.out.println("Please input the size of the array.");
size = x.nextInt();
char[] test = new char[size];
System.out.println("Please input " + size + " characters.");
//ask user to input number of characters
for(int i = 0; i<size; i++){
**test[i] = a.next().toCharArray();**
}
int s;
int e;
System.out.println("Please input the starting value of the search.");
s = x.nextInt();
System.out.println("Please input the ending value of the search.");
e = x.nextInt();
}
public static int spaceCount(char[]arr, int s, int e){
int count = 0;
if (s<= e) {
count = spaceCount(arr,s+1, e);
/*counter set up to cause an increase of "s" so
* the array is traversed until point "e"*/
if (arr[s] == ' ' ) {
count++;
}
}
return count;// return the number of spaces found
}
}
when you force to run your code, you get such error stack
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - incompatible types: char[] cannot be converted to char
at test4c.Test4c.main(Test4c.java:26) Java Result: 1
It is obviously clear why you get such a message?
you try to insert a char array inside an index of char[] test which accept a char not a char array
This is what you have:
for(int i = 0; i<size; i++){
test[i] = a.next().toCharArray();
}
From what you have, I think you want just to convert to a.next() to char array which is test which you have already defined
char[] test = new char[size];
you can change what you have to
test = a.next().toCharArray();
The issue is that the toCharArray returns an array, and you can't put an array into an array. Try this:
Char[] test = a.next().toCharArray();

How to read multiple Integer values from a single line of input in Java?

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`

Categories