Issues with int arrays - java

I'm trying to replicate a DFA/NFA machine with printing transitions.
And am reaching errors when attempting to access values from my preset array and assign them to the newState variable.
So far I've tried moving variables within scope bodies, re-assigning variables and separating the try catch function to ensure the values of binaryValue and state are actually being correctly set.
The exception that occurs is array out of bounds. However i don't see what values requested are out of bounds.
Any help and advice would be appreciated
public class BinaryStringChecker {
private static boolean checker;
public static void main(String[] args) {
//user inputed variable
String userValue;
//checker for binary values variable
checker = false;
//NFA/DFA start State
int state = 0;
//transition array
int stateArray [][] = {{1,0},{2,0},{5,3},{4,4},{5,3},{6,4},{6,6}};
//User input
Scanner usersInput = new Scanner (System.in);
//Introduction
System.out.println("Implimented DFA, will accept binary strings over alphabet Σ= {0, 1} that contain two pairs of adjacent 0’s separated by an even number of alphabet symbols.");
//do while to check if values only consist of 0s and 1s
do{
System.out.println("Please enter desired string: ");
userValue = usersInput.next();
if (userValue.matches("[01]+")) {
System.out.println("Checking "+userValue);
checker = true;
usersInput.close();
}
else {
System.out.println("Thats not a binary number");
}
}
while (checker == false);
//assigning users input value
String str = userValue;
//taking binary list from STL class
STL.StringtoList(str);
//assigning list
List<Character>
chars = STL.StringtoList(str);
//getting binary string length
int stringLength;
stringLength = chars.size();
// Print the list of characters
System.out.println(chars);
//sequential iteration through users binary string
for (int i=0; i<stringLength; i++) {
//taking value from position in list
Character binaryValue = chars.get(i);
try {
int newState = stateArray[state][binaryValue];
state = newState;
System.out.println("Current state:"+state);
}
catch(Exception e) {
System.out.println("Somethings wrong here 1");
}
}
}
}

Related

Reading a file with Strings and floats and assigning them to arrays

I want to design a code that can read a file that looks like this:
Jake 12.00 13.24 6
Sarah 11.23 24.01 8
Alex 10.65 19.45 4
I need to make separate arrays for the Strings, the first float, the second float, and the int.
How do I go about doing this?
This is what I have so far: I'm not sure how to make separate arrays for the two floats. I also keep getting an exception IndexOutOfBoundsException: 0 at EmployeePay.main..
import java.util.Scanner;
import java.io.*;
public class EmployeePay {
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);
int lineNumber = 0;
while (scanner.hasNextLine()){
lineNumber =lineNumber +1;
String [] Identification= new String [lineNumber-1];
int [] TotalDeductions = new int [lineNumber-1];
float [] WorkTime = new float[lineNumber-1];
if(scanner.hasNextInt()){
TotalDeductions[lineNumber-1] = scanner.nextInt();
System.out.println(TotalDeductions[lineNumber-1]);
}
else if (scanner.hasNextFloat()){
WorkTime[lineNumber-1]= scanner.nextFloat();
}
else {
Identification[lineNumber-1] = scanner.next();
System.out.println(Identification[lineNumber-1]);
}
}
}
}
I will assume your String value doesn't contain space. This is kind of pseudo code, Try yourself and explore each line why I did so:
String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
String x = "Jake 12.00 13.24 6";
String[] arr = x.split(" ");
s[i] = arr[0];
f1[i] = Float.valueOf(arr[1]);
f2[i] = Float.valueOf(arr[2]);
}
This error exception IndexOutOfBoundsException: 0 at EmployeePay.main. is occuring due to this statement if (args.length != 1).
It should be if(args.length!=0)
If no arguements are passed at command prompt then args.length is 0. So, this statement will throw an exception final String inputFileName = args[0];
Thus, you need to check for args.length
If your data file is indeed as you show in your post with blank lines between the data lines then you will need to take care of those as well while reading the file and processing the information obtained. You obviously want to skip past those particular lines. If this isn't the case then it only goes to show you how important it is to provide full and accurate information when asking a question here. No one here wants to really assume anything.
When creating arrays it's always nice to know how big an array needs to be beforehand so that you can properly initialize it to its required size. This is where List or ArrayList is better, you can just add to them when needed. Never the less, to properly initialize all your different arrays (String[], float[], float[], and int[]) you need to know how many valid data line are contained within your data file. By valid data lines I mean lines that actually contain data, not blank lines. So the first natural step would be to count those lines. Once you have the count then you can initialize all your arrays to that line count.
Now all you need to do is re-read the file data line by line, split each line to acquire the data segments , then convert each numerical segment to its respective Array data type. Once you have all your arrays filled from the file you can then do whatever you like with the data contained within those arrays. The code to carry out this task might look something like this:
String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
// Count the total number of valid data lines
// within the file (blank line are skipped).
scanner = new Scanner(new File(inputFileName));
while (scanner.hasNextLine()) {
String strg = scanner.nextLine().trim();
if (!strg.equals("")) { linesCount++; }
}
// Declare our different Arrays and size them to
// the valid number of data lines in file.
String[] employeeID = new String[linesCount];
float[] hours = new float[linesCount];
float[] wageRate = new float[linesCount];
int[] deductions = new int[linesCount];
// Read through the file again and place the data
// into their respective arrays.
scanner = new Scanner(new File(inputFileName));
int counter = 0;
while (scanner.hasNextLine()){
// Get the next line in file...
String strg = scanner.nextLine().trim();
// If the file line is blank then skip it.
if (strg.equals("")) { continue; }
// otherwise split the line by its space
// delimiter ("\\s+" takes care of 1 OR more
// spaces just in case).
String[] values = strg.split("\\s+");
// Add to the employeeID string array.
employeeID[counter] = values[0];
// Control what is placed into the elements of each
// float or integer array. If there is no value data
// supplied in file for the employee Name then make
// sure 0.0 (for floats) or 0 (for integers) is placed
// there after all, you can't parse a null string ("").
if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
else { hours[counter] = 0.0f; }
if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
else { wageRate[counter] = 0.0f; }
if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
else { deductions[counter] = 0; }
counter++;
}
scanner.close();
// Now that you have all your arrays you can
// do whatever you like with the data contained
// within them:
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
for (int i = 0; i < employeeID.length; i++) {
System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }

Comparing two String arrays storing integer values separated by "#"

I have to compare two String arrays with integer values separated by "#" input by the user as follows:
Input 1: Size of the array:
3
Input 2: (Array 1)
1#4#5
3#6#7
5#8#9
Input 2: (Array 2)
1#3#5
4#6#7
5#7#9
They contain the same no. of integer strings per line as specified by the user input array size. For eg: the 1st line of Array 1 = 1#4#5 = 3 integer strings.
In case, the array inputs are blank in any line, the output should be "invalid".
The output should be "yes" if the integer values in both the arrays are same irrespective of their position in the array i.e. if they are equivalent, otherwise the output should be "no".
My code passes very few test cases and mostly gives the correct output only when the two arrays are transpose of each other (when seen from the input format). It does not give the correct output when all the integer strings in both the arrays are same irrespective of their positions in the array.
eg. 1: Test case passed:
The output for the arrays in the example above is yes
eg.2: Test case failed:
Input 1: Size of the array:
2
Input 2: (Array 1)
1#6
3#4
Input 2: (Array 2)
6#3
4#1
Output: no
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
public class StringComparison
{
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
// Input the array size
System.out.println("Enter the array size:");
int size = input.nextInt();
input.nextLine();
String[] s1 = new String[size];
String[] s2 = new String[size];
// Input 1st array elements
System.out.println("Enter the 1st array elements:");
for (int i=0;i<size; i++)
{
s1[i]= input.nextLine();
}
// Input 2nd array elements
System.out.println("Enter the 2nd array elements:");
for (int i=0;i<size; i++)
{
s2[i]= input.nextLine();
}
// Check for equivalence
System.out.println(equivalent (size, s1, s2));
}
public static String equivalent (int input1, String[]input2, String[]input3)
{
String result =null;
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
char []b1 = new char[input1*input1];
char[]b2 = new char[input1*input1];
int[] num1 = new int[input1*input1];
int[] num2 = new int[input1*input1];
for (int i=0; i<input1;i++)
{
String[] a1 = input2[i].split("#");
// if the user inputs are less or more than required
try
{
for (int j=0;j<input1;j++)
sb1.append (a1[j]);
}
catch (java.lang.ArrayIndexOutOfBoundsException e)
{
result ="invalid";
return result;
}
}
for (int i=0; i<input1;i++)
{
String[] a2 = input3[i].split("#");
// if the user inputs are less or more than required
try
{
for (int k=0;k<input1;k++)
sb2.append (a2[k]);
}
catch (java.lang.ArrayIndexOutOfBoundsException e)
{
result ="invalid";
return result;
}
}
// Storing the contents of the StringBuilder objects in a char array
sb1.getChars (0,((input1*input1)-1),b1,0);
sb2.getChars (0,((input1*input1)-1),b2,0);
// Converting the elements of the char array into integers and storing it in an int array
for (int p=0; p<((input1*input1)-1);p++)
{
num1[p] = Character.digit( b1[p],(input1*input1)-1);
}
// Converting the elements of the char array into integers and storing it in an int array
for (int q=0; q<((input1*input1)-1);q++)
{
num2[q] = Character.digit( b2[q],(input1*input1)-1);
}
// Sorting the two integer arrays
Arrays.sort (num1);
Arrays.sort (num2);
if (Arrays.equals (num1,num2))
{
result = "yes";
}
else
{
result ="no";
}
return result;
}
}
i have rewritten your equivalent method. i hope its okay to use ArrayList.
private static String equivalent(String[] s1, String[] s2) {
ArrayList<Integer> num1 = new ArrayList<Integer>();
ArrayList<Integer> num2 = new ArrayList<Integer>();
for (String str : s1) {
String[] storage = str.split("#");
for (String st : storage) {
num1.add(Integer.parseInt(String.valueOf(st)));
}
}
for (String str : s2) {
String[] storage = str.split("#");
for (String st : storage) {
num2.add(Integer.parseInt(String.valueOf(st)));
}
}
Collections.sort(num1);
Collections.sort(num2);
if (num1.equals(num2)) {
return "yes";
} else {
return "no";
}
}
this does what you want to achieve with fewer code. if you need help understand or have any other questions feel free to ask
The logic you are using to make the integer array is wrong and it produced invalid entries.Try printing the array values.All the test cases will fail.
Try below to convert the the char into the integer
num2[q] = Integer.parseInt(String.valueOf(b2[q]));
num1[p] = Integer.parseInt(String.valueOf(b1[p]));
Note:Example 1 should have been "NO". There is no 8 in the second input.

To find the substring from string without library.I know its an easy one but i cant find where I am getting struck with that if statement

package stringoperation;
import java.util.Scanner;
public class Stringops {
public static void main(String [] args)
{
String string ;
String sub ;
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
string =in.nextLine();
System.out.println("enter a substring to identify");
sub = in.nextLine();
char[] array= string.toCharArray(); // converting string to array of char
char[] subarray = sub.toCharArray(); //converting sub string to array of char
int count=0;
for(int j=0;j<array.length;j++)
{
if(array[j]==subarray[count]) //till both are same it will run
{
if(count==sub.length()-1) //if substring size is reached thats mean matched break out
{
System.out.println("substring is present");
break;
}
j++;
}
if(array[j]!=subarray[count]) // otherwise make count as 0 to proceed again
{
count=0;
}
}
}
}
The if statement I checked still can't find the error. I am missing something. Just tell me what I am doing wrong.
Try using string.indexOf(sub) != -1, after you're certain that the input strings are in the format you expect; i.e. control characters such as newlines aren't appended to your input data. It's necessary to keep in mind that comparisons will be failed if the Strings you're comparing don't match exactly, i.e.
"example" != "Example".

I am trying to compare 2 sets of integer values to check for a match in a lottery ticket scenario

I am fairly new to Java and am struggling with this concept. As I have said I am trying to make a comparison between 2 sets of integer values, one set I have retrieved from the website using HTML parsing and stored in an array (Integer [] numbers = new Integer[split.length]).
The other set of values I have retrieved from user input and have stored in the array userNumbers (int userNumbers = new int [SIZE]). I attempted to use the if condition to make the comparison i.e. if (userNumber[count] == number [0]).
However I am getting errors and the IDE is not allowing me to enter the number array part of the comparison. Can anyone help me to understand why this is or instruct me as to what I may be doing wrong? Here is the code in full.
Help is very much appreciated in advance.
public class lotteryNumbers
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//link to the intended web site
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
//Elements elementsHtml = doc.getElementsByTag("main-article-content");
} catch (IOException e) {
e.printStackTrace();
}
final int SIZE = 7;
//array to store user numbers
int [] userNumbers = new int[SIZE];
//array to check if user number is present with web numbers
boolean [] present = new boolean[7];
int counter = 0;
while (counter<SIZE)
{
System.out.println("enter your numbers");
userNumbers[counter]=keyboard.nextInt();
counter++;
}
for (int count: userNumbers)
System.out.println(count);
if (userNumbers[0] == )
The numbers local variable is declared in the try{...} block. Thus it is not accessible outside it.
If you declare it before the try{ line it will work:
Integer[] numbers;
try {
...
// set numbers here
...
} catch (IOException e) {
...
}
// can use numbers here
If it is the only value you need from the HTML-parsing code you may even refactor the try/catch structure to a method returning the data for numbers.
And by the way, I advise you not to try int == Integer, prefer int == int. It is usually clearer and you won't have to guess if the int will be boxed or the Integer unboxed.

Java how do you convert lower case string values to upper case ones in a string array

I have this problem and i want it that when a user enters a lower case word. I want my program to take lower case strings in array and upper case strings in an array.
/**
The ObjectSelectionSorter class provides a public static
method for performing a selection sort on an numbers of
objects that implement the Comparable interface.
*/
public class ObjectSelectionSorter
{
/**
The selectionSort method performs a selection sort on an
numbers of objects that implement the Comparable interface.
#param numbers The numbers to sort.
*/
public static void selectionSort(Comparable[] numbers)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
Comparable minValue; // The smallest value found in the scan
// The outer loop iterates once for each element in the
// numbers. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (numbers.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = numbers[startScan];
// Scan the numbers, starting at the 2nd element in
// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < numbers.length; index++)
{
if (numbers[index].compareTo(minValue) < 0)
{
minValue = numbers[index];
minIndex = index;
}
}
// Swap the element with the smallest value
// with the first element in the scannable area.
numbers[minIndex] = numbers[startScan];
numbers[startScan] = minValue;
}
}
}
import java.io.*;
/**
This program demonstrates the search method in
the IntBinarySearcher class.
*/
public class BinarySearchTest
{
public static void main(String [] args) throws IOException
{
int result;
String searchValue;
String input;
// An array of numbers to search.
String[] numbers = {"Jake", "Jerry", "Bill", "Lousie", "Goku", "Ivan", "John", "Sarah", "Kim"};
// Create the console input objects.
InputStreamReader reader =
new InputStreamReader(System.in);
BufferedReader keyboard =
new BufferedReader(reader);
// First we must sort the array in ascending order.
ObjectSelectionSorter.selectionSort(numbers);
do
{
// Get a value to search for.
System.out.print("Enter a value to search for: ");
input = keyboard.readLine();
searchValue = input;
// Search for the value
result = ObjectBinarySearcher.search(numbers, searchValue);
// Display the results.
if (result == -1)
System.out.println(searchValue + " was not found.");
else
{
System.out.println(searchValue + " was found at " +
"element " + result);
}
// Does the user want to search again?
System.out.print("Do you want to search again? (Y or N): ");
input = keyboard.readLine();
} while (input.charAt(0) == 'y' || input.charAt(0) == 'Y');
}
}
/**
The StringBinarySearcher class provides a public static
method for performing a binary search on an String array.
*/
public class ObjectBinarySearcher{
/**
The search method performs a binary search on an String
array. The array is searched for the number passed to
value. If the number is found, its array subscript is
returned. Otherwise, -1 is returned indicating the
value was not found in the array.
#param numbers The array to search.
#param value The value to search for.
*/
public static int search(String[] numbers, String value)
{
int first; // First array element
int last; // Last array element
int middle; // Mid point of search
int position; // Position of search value
boolean found; // Flag
// Set the initial values.
first = 0;
last = numbers.length - 1;
position = -1;
found = false;
// Search for the value.
while (!found && first <= last)
{
// Calculate mid point
middle = (first + last) / 2;
// If value is found at midpoint...
if (numbers[middle].equals(value))
{
found = true;
position = middle;
}
// else if value is in lower half...
// need tell is value is less then the integer?, with out using equality regulators
else if (value.compareTo(numbers[middle]) < 0)
{
last = middle - 1;
}
// else if value is in upper half....
else
first = middle + 1;
}
// Return the position of the item, or -1
// if it was not found.
return position;
}
}
Try this:
String[] numbers = {"Jerry"};
numbers[0] = numbers[0].toUpperCase();
There's string.toUpperCase() and Character.toUpperCase(char). The former returns a string that is the upper-case version of the given string, and the latter returns the uppercase version of a char. (I'm giving the latter because you mention an array, and it might be an array of chars that you mean)

Categories

Resources