Getting The Array Index From string.toCharArray() - java

I am making an inefficient calculator type of program that takes values from user defined arrays and plugs them into an equation that the user also defines. To do this I needed to make my program change my string to a char array, the problem? I have it so that users must use A1-10 to reference the definded index and I cannot find a way to make the program search the next array for the number to specify what array the program is accessing.
out.println("Please input a string of commands in a format similar to this: ");
out.println("([A1]-[A2]=) or ([A8]+[A6]=) or ([A1]-[A4]+[A7]*[A10]/[A3]=)");
out.println("Use only the numbers 1-10 when referencing an array. \n You may always type in 'Help' if you need help. ");
String eString = scn.nextLine();
if ("help".equals(eString)) {
out.println("Figure it our yourself...");
} else {
for (char c: eString.toCharArray()) {
if (c == 'A') {
}
}
the code got a little jumbled up while changing code and I haven't taken the time to make it look nice and pearly again.

If you need the index you should just use a normal for loop instead of an enhanced for loop.
char[] input = eString.toCharArray();
for(int i = 0; i < input.length; i++) {
if(input[i] == 'A'){
// You know the index of A here.
}
}
You should also use "help".equalsIgnoreCase(eString) when comparing with help so that they can enter either "Help" or "help" (link to doc)

Related

how do you use a string in a while loop and then number the string?

in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)
C
a
r
o
l
i
n
e
Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far
Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:
Find the length of your string
Use the while loop, with the condition relating to the length of your string, to move through the string character by character
Print out to a newline each individual character in your string
Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.
In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i=0;
string s;
cin>>s;
while(i<s.length())
{ cout<<i+1<<"."<<cout<<s[i]<<endl;
i++;
}
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}
This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.
inside your main method try this:
//Asks user name.
System.out.println("What's your name?");
//Instantiates scanner
Scanner sc = new Scanner(System.in);
//With the scanner it reads user input and save it in the variable name
String name = sc.nextLine();
//It is a good programming practice to close the scanner
sc.close();
/*The loop that for each letter of the name also prints the position
number plus 1*/
int i = 0;
while (i < name.length()) {
System.out.println(i+1 + ". " + name.charAt(i));
i++;
}
As per snap shot shared by OP:
Here, you need to modify this lines:
System.out.println(name.charAt(i));
to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));
Also, change this line:
i++;
}}}
to
i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}

ArrayIndexOutOfBoundsException when putting strings split from an array into 3 others [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is my code:
for (int i = 0; i < 99; i++)
{
String inputString = keyboard.next();
String[] inputArray = inputString.split(":");
if (inputString.equals("quit"))
System.out.println("You have quit");
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
So here is my code, I'm trying to test out arrays and I need to get input from the user split using the delimiter ":"
I had to parseInt the last two arrays (as they are taking in integer values) to get the split input from the second and third index of the inputArray.
I have the last part of the code to test if it works, and it does but when I type in "quit" to end the loop it throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
I have searched and understood the issue but don't know how to avoid it. Sorry if I'm not explaining my issue, would appreciate another working solution. Thanks in advance for help
The string "quit" does not contain any ":" characters, so the result of inputString.split(":") is an array with a single element. So as soon as you try to access inputArray[1], you will have the exception, because index 1 refers to the 2nd element in the array, although this array has only one element
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // add this line
}
Add the return statement (shown above), and this will by pass the code problematic code. It seems like the right thing to do anyways, as the user is asking to quit the program.
Access inputArray only till its length i.e use inputArray.length() first to find array length then access array elements from 0 to length -1.
Most evident case from your code is when you enter quit but other inputs might cause it too since your are not checking length of array i.e. if length of splitted array is less that 3 for whatever input , you will receive this exception.
The issue you are running into is that the code accessing the inputArray variable is run regardless of whether or not the quit command is received. You have two options here.
1) Return on the quit command (recommended)
if (inputString.equals("quit")) {
System.out.println("You have quit");
return; // This will avoid running the code below
}
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
2) Throw the remaining code in an else case
if (inputString.equals("quit")) {
System.out.println("You have quit");
} else {
FirstArray[i] = inputArray[0];
SecondArray[i] = Integer.parseInt(inputArray[1]); // these throw errors
ThirdArray[i] = Integer.parseInt(inputArray[2]);
System.out.println(FirstArray[i]);
System.out.println(SecondArray[i]);
System.out.println(ThirdArray[i]);
}
I would also recommend adding an error case if the inputArray doesn't end up being the expected length.
if (inputArray.length != 3) {
System.out.println("That's weird. I was expecting 3 parameters, but only found " + inputArray.length);
return;
}
you can use Scanner class to read the input.
Scanner scanner = new Scanner(System.in);
for(int i=0; i<Noofiterations; i++){ //iterations are the no.of times you need to read input.
String[] inputArray = scanner.nextLine().split(":");
//rest of the code is same as yours.
}
Input should be in the form "abc:123:334:wet"
Hope this helps. Let me know if i didn't get your question.

trying to separate strings from an array with strings and ints (current program included)

This is my current program for taking input and giving the user a total pay over two days. I am currently trying to separate strings from a string array (Made after .split(", ")) and put those strings into its own array to process. I am also doing this same process with integers but so far I can't get the string separation to work properly. any help will be appreciated.*note, I am a somewhat beginner with this and only took one class so far so please keep it simple.
import java.util.Scanner;
public class AmusementPark
{
public static void main(String[] args)
{
Scanner Reader=new Scanner(System.in);
int [] WorkScheduleInts;
String [] WorkScheduleStrings=new String[8];
System.out.println("Please enter the work schedule as follows:");
System.out.println("125, 2, 1, 7, 125, 3, 5, H");
System.out.println("Enter Your work schedule:");
String WorkScheduleinput=Reader.nextLine();
String [] WorkScheduleSplit=new String[8];
WorkScheduleSplit=WorkScheduleinput.split(", ");
for(int x=0; x<WorkScheduleSplit.length;x++)
{
if(WorkScheduleSplit[x]=="A" || WorkScheduleSplit[x]=="B" || WorkScheduleSplit[x]=="C" || WorkScheduleSplit[x]=="D" || WorkScheduleSplit[x]=="E" || WorkScheduleSplit[x]=="F" || WorkScheduleSplit[x]=="G" || WorkScheduleSplit[x]=="H")
{
WorkScheduleStrings[x]=WorkScheduleSplit[x];
}
System.out.println(WorkScheduleStrings[x]);
}
}
}
Edit: Saw the comment on variables starting with a lower case and realized i missed that. Woops.
The problem that I see is that you put the H into the last place of workScheduleStrings. The first 7 places of workScheduleStrings won't get initialized but the last place will end up holding an H. What you need is another integer variable to count how many items have been placed into workScheduleStrings. Start it at 0 and change
workScheduleStrings[x] = workScheduleSplit[x];
to
workScheduleStrings[count] = workScheduleSplit[x];
After that you should increment count by one. Also you should check for equivalence with
workScheduleSplit[x].equals["H"];
You also have some body (brace) placement problems it looks like. I think both statements under the if statement should execute if the if statement evaluates true. Right now if will do the assignment if true but will always try to output. This could be a problem if you try to output uninitialized memory. If you do this it will only output an H but I assume you intend to take care of the integer parts of workSheduleSplit later. Really I think that should happen first. Anyway,
The loop now looks like:
int count = 0;
for(int x=0; x<workScheduleSplit.length;x++){
//I leave out the comparisons of A-G because I'm lazy. You have that part if you use the equals method though.
if( workScheduleSplit[x].equals("H"){
workScheduleStrings[count]=workScheduleSplit[x];
System.out.println(workScheduleStrings[count]);
count++;
}}
Use following way to compare strings inside the if statement,
WorkScheduleSplit[x].equals("H")
Instead of == use String.equals
Read this link to understand the difference between String.equals and == operations.

Preventing duplicate scanner user input

This program I am writing is giving me fits. What I am trying to do is prevent a user from entering the same integer twice. The program takes 4 int inputs and compares them to an array of 4 random int's, searching for a match. Here is what I have thus far in my attempts to prevent multiple inputs.
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
temp[z] = inputDevice.nextInt();
for(int why = 0; why<temp.length; why++){
if(Arrays.asList(temp).contains(temp[z])){
System.out.println("Duplicate found! Please enter a non-repeating digit");
temp[z]=0;
z--;
}
}
}
The inputs are coming into the temp array just fine. And are being passed on to the other methods in the program, and that is working. I am guessing the issue is with my conditional statement - if(Arrays.asList(temp).contains(temp[z]))
Is there a better way to test to see if an array already contains a value?
Thanks in advance.
1) Since you are converting the array to a list, might as well use an ArrayList
2) Store your input in a variable and test if it is contained within the list already
List<Integer> my_list = new ArrayList<Integer>();
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
int input = inputDevice.nextInt();
if(my_list.contains(input)){
System.out.println("Duplicate found! Please enter a non-repeating digit");
z--;
}
else{
my_list.add(input);
}
}
When you check if temp contains z, it already contains z. Put the input in a temporary variable before you check it and only add it afterwards.
You're not using the why from your loop.
However if possible I would change temp to an ArrayList implementation. The problem with toList method. It's using the int[] array as a single object rather than treating it as an array of int objects. To do the latter you must use Integers.

Do-while loop won't escape - Java

Does a do-while loop check a value before or after it has been incremented? I can't seem to make this do-while loop escape, and can't determine if that is the mistake I am making. The point of this loop is to take input from the user and when they hit 'X', I want the loop to end. Am I using the wrong type of loop, or perhaps an incorrect statement?
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(coefficient[i] != "X");
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Specifically in your case, I'd change
} while(coefficient[i] != "X");
to something like:
} while(!"X".equalsIgnoreCase(coefficient[i]));
And you've got another problem in your code in that you want to test the user input which you place into coefficient[i], but then you promptly increment the i variable such that coefficient[i] no longer refers to the input.
So perhaps the test should instead be:
} while(!"X".equalsIgnoreCase(coefficient[i - 1]));
You're incrementing i between coefficient[i] = keyboard.nextLine(); and while(coefficient[i] != "X");, so in the while check coefficient[i] is null, also use .equals to compare strings.
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(!coefficient[i-1].equals("X"));
There is two problems here. First you shouldn't compare Strings using logical operators. Use .equals instead.
For example:
coefficient[i].equals("X");
Secondly you are incrementing your array index counter before you check the while condition. So you actually need to subtract one from it to check if the most recently entered String was X.
See if using this will get it working:
coefficient[i-1].equals("X");

Categories