Creating array with unknown elements by Input them - java

I know this isn't something you are supposed to do yet but I'm still trying to figure out a way to run this loop, an letting the arr[i] inside it "know" about the rise of the number of elements in the array (which I declare outside of the loop because I don't want it to make a new one each time).
int counter=1, note=0;
System.out.println("Please enter characters, -1 to stop: ");
do {
char[] arr= new char[counter];
for (int i=0;i<=counter;i++){
arr[i] = s.next().charAt(0);
if (arr[i]==-1){
note = -1;
break;
}
++counter;
}
} while (note>=0);

From your much clearer comment, this is an example main method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Input
int amt = 0; // Amount of chars received
List<Character> chars = new ArrayList<>(); // ArrayList is easier for now
while (input.hasNext()) { // Grabs Strings separated by whitespaces
String token = input.next(); // Grab token
if (token.equals("-1")) {
break; // End if -1 is received
} else if (token.length() != 1) {
throw new IllegalArgumentException("Token not one char: " + token);
// It seems you want only chars - this handles wrong input
} else {
chars.add(token.charAt(0)); // Adds the character to the list
amt++; // Increment amt
}
}
char[] array = new char[amt]; // Converting to an array
for (int i = 0; i < amt; i++) {
array[i] = chars.get(i); // Copies chars into array
}
System.out.println(Arrays.toString(array)); // Handle data here
}
I hope that this is correct. An input of a b c d -1 leads to an output of [a, b, c, d].

If you use the Input String size check I think as you will be resolved.
int counter=0, note=0;
System.out.println("Please enter characters, -1 to stop: ");
String input=s.nextLine();
counter=input.length();
char[] arr= new char[counter];
for (int i=0;i<counter;i++){
arr[i] = input.charAt(i);
}
and If you are using the ArrayList rather than Array is no need to worry about the size.
ArrayList is effective flexable data
cause using add function.

Related

Take input of number of elements of an array, and input the array and display the odd and even elements of the array in their specified arrays

I have written the question I have to write the code for in the title but I am getting certain errors in my code.
The errors are:
line 7: numOfVal cannot be resolved or is not a field
line 23: numOfVal cannot be resolved to a variable
line 25: cannot invoke add(int) on the array type int[]
line 28: cannot invoke add(int) on the array type int[]
line 47: oddarray cannot be resolved to a variable
line 48: evenarray cannot be resolved to a variable
I would be very grateful if you could help me fix the errors in my code.
Thanks.
import java.util.Scanner;
public class CountEvenOddArray {
int[] mainarray;
void setInpLength(int numOfVal) {
this.numOfVal = numOfVal;
}
void setVal(int index,
int Val) {
this.mainarray[index] = Val;
}
void MainArrays() {
mainarray = new int[100];
}
void EvenOdds() {
int evenarray[] = new int[100];
int oddarray[] = new int[100];
for (int i = 0; i <numOfVal ; i++ ) {
if (mainarray[i]%2 == 0) {
evenarray = evenarray.add(mainarray[i]);
}
else {
oddarray = oddarray.add(mainarray[i]);
}
}
}
public static void main(String[] args) {
CountEvenOddArray abc = new CountEvenOddArray();
int numOfVal;
int mainarray[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements you want to store:");
numOfVal = sc.nextInt();
abc.setInpLength(numOfVal);
System.out.println("Enter the elements of the array: ");
for (int k = 0; k < numOfVal; k++ ) {
abc.setVal(k, sc.nextInt());
}
abc.EvenOdds();
sc.close();
System.out.println("The array with the odd elements is:" + oddarray);
System.out.println("The array with the even elements is:" + evenarray);
}
} ```
Here is a runnable example of how this task could be accomplished. You will notice that there are very few methods required. Having too many methods to carry out single simple tasks that can be accomplished with single lines of code just makes things harder to follow and bloats the application. Be sure to read the comments within the code:
import java.util.Scanner;
public class CountEvenOddArray {
// Class member variables:
private final String LS = System.lineSeparator();
private int[] mainArray;
// Startup main() method (Application entry point):
public static void main(String[] args) {
// App started this way to avoid the need for statics:
new CountEvenOddArray().startApp(args);
}
private void startApp(String[] args) {
/* Open a keyboard input stream. You only ever need one
of these in any console application. Do not close this
stream unless you know for sure that you will never need
it again during your application session otherwise, you
will need to restart the application to use it again.
The JVM will automatically close this resource when the
application ends. */
Scanner sc = new Scanner(System.in);
// Get the desired size of Main Array from User:
String numOfElems = "";
while(numOfElems.isEmpty()) {
System.out.println("Enter number of elements you want to store or");
System.out.print( "enter 'q' to quit: -> ");
numOfElems = sc.nextLine().trim();
// Is Quit desired?
if (numOfElems.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(numOfElems)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + numOfElems + ") Try again..." + LS);
numOfElems = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer:
int numOfElements = Integer.parseInt(numOfElems);
// Initialize mainArray{}:
mainArray = new int[numOfElements];
// Have User enter the elements for the Array (with validation):
System.out.println();
System.out.println("Enter the elements of the array ('q' to quit):");
for (int i = 0; i < numOfElements; i++ ) {
// Prompt for each required mainArray[] Element:
String elem = "";
while (elem.isEmpty()) {
System.out.print("Enter Element #" + (i+1) + ": -> ");
elem = sc.nextLine().trim();
// Is Quit desired?
if (elem.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(elem)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + elem + ") Try again..." + LS);
elem = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer element:
int element = Integer.parseInt(elem);
mainArray[i] = element;
}
/* mainArray[] is now initialized and filled. We will now create
the oddArray[] and evenArray[] from what is in the mainArray[]
but, because we have no idea what the User may have entered
for element values, there is no real viable way to create exact
fixed length int[] odd or even arrays unless we count them first.
This would require additional iterations basically meaning, we
are doing the job twice. We can get around this by placing our
odd/even results into a couple of List<Integer> Lists (which can
grow dynamically) then converting them to array later (if desired): */
java.util.List<Integer> odd = new java.util.ArrayList<>();
java.util.List<Integer> even = new java.util.ArrayList<>();
/* Determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. */
evenOdds(odd, even);
// Convert Lists to int[] Arrays....
// Convert List<Integer> odd to oddArray[]:
int[] oddArray = odd.stream().mapToInt(d -> d).toArray();
// Convert List<Integer> even to evenArray[]:
int[] evenArray = even.stream().mapToInt(d -> d).toArray();
// Display the oddArray[] and the evenArray[]...
System.out.println();
System.out.println(oddArray.length + " odd elements are in the oddArray[]: -> "
+ java.util.Arrays.toString(oddArray));
System.out.println(evenArray.length + " even elements are in the evenArray[]: -> "
+ java.util.Arrays.toString(evenArray));
}
/* Method to determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. The
Lists are added to by way of reference to them therefore no returnable
objects are required.
*/
private void evenOdds(java.util.List<Integer> odd, java.util.List<Integer> even ) {
for (int i = 0; i < mainArray.length ; i++ ) {
if (mainArray[i] % 2 == 0) {
even.add(mainArray[i]);
}
else {
odd.add(mainArray[i]);
}
}
}
public boolean isInteger(String value) {
boolean result = true; // Assume true:
// Is value null or empty?
if (value == null || value.trim().isEmpty()) {
result = false;
}
/* Is value a match to a string representation of
a integer value? */
else if (!value.matches("\\d+")) {
result = false;
}
// Does value actually fall within the relm of an `int` data type?
else {
long lng = Long.parseLong(value);
if (lng > Integer.MAX_VALUE || lng < Integer.MIN_VALUE) {
result = false;
}
}
return result;
}
}
If run and your entries are like this within the Console Window:
Enter number of elements you want to store or
enter 'q' to quit: -> 5
Enter the elements of the array ('q' to quit):
Enter Element #1: -> 1
Enter Element #2: -> 3
Enter Element #3: -> 2
Enter Element #4: -> 5
Enter Element #5: -> 4
You should see something like this:
3 odd elements are in the oddArray[]: -> [1, 3, 5]
2 even elements are in the evenArray[]: -> [2, 4]

unable to update the output

I am trying to write a code to play hangman and it is working correctly but every time when I input a character, it resets my output. Can someone please help.
my code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (char i : word.toCharArray()){
if(input == i){
System.out.print(input);
continue;
}
System.out.print("_");
}
}
}
}
A small piece of the output:
______
hint: It is a fruit
Enter a character:
a
__a___
Enter a character:
o
o_____
Enter a character:
r
_r____
Enter a character:
n
___n__
Enter a character:
When I enter 'a' it prints it correctly but when I enter some other character it prints that character an not 'a'. Can somebody pls tell me what should I do to get the correct output.
It looks like you are not saving the string with the character added to the game, you are only printing it. You will probably want to do something like add the new character to the string variable _ask rather than printing as you go, then print after the for loop has run. Basically you are not storing the past rounds anywhere.
As mentioned in the other answer you need to remember the characters from previous attempts. This could for example be done like this:
String tempAsk = "";
for (char i : word.toCharArray()){
if(input == i){
tempAsk += i;
} else {
tempAsk += ask.charAt(i);
}
}
ask = tempAsk;
System.out.println(ask);
I think that,
In the loop for (char i : word.toCharArray()),
you should add the character to ask (or have another string variable named ans),
and then print ask at the end of the loop
because you are not updating the value of ask and printing the place of the character in the string,
and when the loop runs a second time it doesn't show the last character that u entered
plus you can have specific hints according to the fruit name using switch case
and maybe have an error pop up when the player enters the wrong character
You can use a character array to check what letters are present so far like so:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
// Create a character array to store the result so far
char[] result = new char[word.length()];
//Fill the array with _
Arrays.fill(result, '_');
System.out.println(new String(result));
System.out.println("hint: It is a fruit");
int numChances = 15;
for (int j = 1; j <= numChances; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (int i = 0; i < word.length(); i++) {
if(word.charAt(i) == input){
//update the array with user's correct response
result[i] = input;
}
}
// Check how we're doing so far. Make a string with the result
String untilNow = new String(result);
// Show user what we have so far
System.out.println(untilNow);
//Check if the user has guessed the word.
if(untilNow.equalsIgnoreCase(word)) {
System.out.println("You win...");
break;
}
}
}

StringBuilder.insert() not changing output

I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");

Why the array seem to be longer than its maximum length?

Im new, I try to write some code, its for counting the string letter, space, and such. So, i set array length 50. But when i run the code later and enter more than 50 characters, it still can be run,and the total count can be more than 50, why? thank you.
import java.util.Scanner;
public class javaexcrises {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String astrg = new String();
char[] ch = new char[50];
int charcount=0;
int spaccount=0;
int numcount=0;
int othcount=0;
System.out.println("Please enter some word ");
if(scan.hasNextLine()){
astrg = scan.nextLine();
ch = astrg.toCharArray();
int i;
for(i=0;i<astrg.length();i++){
if(Character.isLetter(ch[i])){
charcount++;
}
else if(Character.isDigit(ch[i])){
numcount++;
}
else if(Character.isSpaceChar(ch[i])){
spaccount++;
}
else{
othcount++;
}
}
System.out.println("Character = "+charcount);
System.out.println("Space = "+spaccount);
System.out.println("Number = "+numcount);
System.out.println("Others ="+othcount);
System.out.println("Total = "+ch.length);
}
scan.close();
}
}
ch = astrg.toCharArray();
toCharArray() returns a reference to a NEW array, and that reference replaces the old one that you allocated. That new array is large enough to contain the entire input string.
When we do astrg.toCharArray(), It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
If you remove new char[50] also it will not affect.

JAVA- Returning an Array to main

In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main. When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.
In main:
// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
In getAnswers():
// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
// Loop to receive input into array.
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
array2 = input.toCharArray();
}
return array2;
}
try
array2[index] = input.charAt(0);
after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.
Right now you're creating a new array2 with each input and thereby destroying any previous input with the previous array2 that you created.
If you absolutely need to create a char array, why not append the String answers into a StringBuffer object, and then when done, call toString().toCharArray() on the StringBuffer.
Myself, I'd create an ArrayList and just append the response to the ArrayList and at the end return the ArrayList.
It is not good idea to modify the method param. You can try :
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
String tmp = "";
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
tmp += input.chaAt(0); // check length is > 0 here
}
return tmp.toCharArray();
}

Categories

Resources