So basically I'm passing 3 strings to my constructor which will then place them in already made arrays within my object/class, i'm having a bit of trouble trying to figure this out.
This is my object class
public class results {
String[] matchnumber = new String[9];
String[] score1 = new String[9];
String[] score2 = new String[9];
int i = 0;
public results() {
}
public void addResults(String token, String token2, String token3) {
matchnumber[i] = token;
score1[i] = token2;
score2[i] = token3;
i++;
}
This is my main class
> do {
> System.out.println("Enter the current Round number between 1-26");
> roundnumber = kb.nextInt();
> } while (roundnumber <= 0 || roundnumber >= 27);
> results[] resultsarray = new results[(roundnumber)];
>
> for (int i = 0; i < resultsarray.length; i++) {
> File myFiles2 = new File("Round" + (i+1) +".txt");
> Scanner inputFiles2 = new Scanner(myFiles2);
>
> while (inputFiles2.hasNext()) {
> String str2 = inputFiles2.nextLine();
> String[] token = str2.split(",");
> System.out.println(token[0] + " " + token[1]+ " " + token[2]);
> resultsarray[i].addResults(token[0], token[1], token[2]); (NULL EXCEPTION ON THIS LINE)
> }
> }
As you can see Im scanning a text file to obtain 3 strings (text file contains lines of data). What i need help with is passing the 3 string tokens in my object and then saving it as an array and then processing the next batch of 3 strings into the next array index until i run out of strings in the current text file, whereby the next text file is opened and new instance of the results object is created and rinse and repeat. So yeah am i even close or completely off track lol.
You shouldn't assign values to the arrays in the results constructor, since the constructor only accepts the values for a single index of the array, and your current code will only use the first (0) index of each array.
You should use a constructor that takes no arguments, and use a different method to add the data to the arrays.
Your inner loop will then look like this :
resultsarray[i] = new results();
while (inputFiles2.hasNext()) {
String str2 = inputFiles2.nextLine();
String[] token = str2.split(",");
System.out.println(token[0] + " " + token[1]+ " " + token[2]);
resultsarray[i].addResults(token[0], token[1], token[2]);
}
Where addResults is a new method that contains the logic of your old constructor.
Related
I have a file that contains 30 lines of data in this format:
month-day-year-gas price
Here's some sample data:
May 02, 1994 1.04
Can someone tell me how to load this file in a parallel arrays of months, days, price in java? After this I will have to display the lowest price, and also the highest price, and the average price for each month.
For those who are wondering:
Parallel Arrays are arrays where the data in each array is directly related to any given record data row. The index of one array contains related data at the very same index in another array. For example:
Dimension[] dim = new Dimension[4];
dim[0] = new Dimension(1,11);
dim[1] = new Dimension(2,22);
dim[2] = new Dimension(3,33);
dim[3] = new Dimension(4,44);
int[] widths = {dim[0].width, dim[1].width, dim[2].width, dim[3].width};
int[] heights = {dim[0].height, dim[1].height, dim[2].height, dim[3].height};
for (int i = 0; i < widths.length; i++) {
int w = widths[i];
int h = heights[i];
System.out.println("Width: " + w + " | Height: " + h);
}
And the Console output would be:
Width: 1 | Height: 11
Width: 2 | Height: 22
Width: 3 | Height: 33
Width: 4 | Height: 44
The widths and heights Integer Arrays are considered Parallel Arrays since the data index in each array is directly Related To and Parallel to each other. It doesn't matter which parallel array you iterate through, the current iteration is related to all other parallel arrays.
You can quickly see why it's much better to utilize a Class with Member variables for this sort of thing instead of arrays especially when a multiple number of parallel arrays are involved however, there are some practical uses for it.
The task at hand:
As you read in your file you want to use the String#split() method to break that line into the desired chunks you want. The delimiter to use here for the split() method will be a white-space (" ") or the Regular Expression (RegEx) "\\s+", for example:
"This is my String".split("\\s+");
The RegEx argument within the split() method basically means, split the string on one or more white-spaces.
In the example below the Parallel Arrays are Class Member variables. The method that fills these Arrays with the pertinent data from file is named fillParallelArraysWithFileData() and it accepts one argument, which is the path and name of the data file. Here is the code:
private static String[] monthsArray;
private static int[] daysArray;
private static int[] yearsArray;
private static double[] pricesArray;
public static void fillParallelArrayWithFileData(final String filePath) {
Scanner read = null;
try {
read = new Scanner(new File(filePath));
/* First Read Pass
===============
Get the number of VALID data lines in file.
We need this count to know how large to size
our Parallel Arrays.
*/
int lineCount = 0; // counter
while (read.hasNextLine()) {
String line = read.nextLine().trim(); // Trim lead/trailing whitespaces (if any)
/* Skip past blank or comment lines. Lines that start with
a semicolon (;) or a hash character (#) are considered
comment lines here and are ignored. You can get rid of
those conditions if you like. */
if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
continue;
}
lineCount++; // Increment the counter.
}
/* Second Read Pass
================
Get the file data and fill Arrays...
Declare Arrays which will be our parallel arrays. */
monthsArray = new String[lineCount];
daysArray = new int[lineCount];
yearsArray = new int[lineCount];
pricesArray = new double[lineCount];
int indexIncrementer = 0;
// Start the read from beginning again...
read = new Scanner(new File(filePath));
while (read.hasNextLine()) {
String line = read.nextLine();
// Remove the comma in data line. Don't want it.
line = line.trim().replace(",", "");
// If the current line is blank or a comment then skip past it.
if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
continue;
}
// Split the current data line
String[] lineParts = line.split("\\s+");
monthsArray[indexIncrementer] = lineParts[0];
daysArray[indexIncrementer] = Integer.parseInt(lineParts[1]);
yearsArray[indexIncrementer] = Integer.parseInt(lineParts[2]);
pricesArray[indexIncrementer] = Double.parseDouble(lineParts[3]);
indexIncrementer++;
}
}
catch (FileNotFoundException ex) {
System.out.println("FILE NOT FOUND! [" + filePath + "]");
}
finally {
if (read != null) {
read.close();
}
}
}
And an example usage might be:
// Fill Arrays with File data.
fillParallelArrayWithFileData("GasPrices.txt");
// Get Gas price for month of July in 1994
String desiredMonth = "July";
int desiredYear = 1994;
// We could iterate through any one of the Parallel Arrays
for (int i = 0; i < pricesArray.length; i++) {
if (monthsArray[i].equalsIgnoreCase(desiredMonth) && yearsArray[i] == desiredYear) {
String m = "Date: " + monthsArray[i] + " ";
String d = daysArray[i] + ", ";
String y = yearsArray[i] + " - ";
String p = "Gas Price: $" + pricesArray[i];
System.out.println(m + d + y + p);
}
}
Output to console window would be something like:
Date: July 2, 1994 - Gas Price: $1.12
I have updated my code. I have 3 arraylists and based on the condition I want to update values. I am using for each loop to iterate but now I am doing something wrong with the break it is not resetting/picking up next value for type and len. It is only resetting name.
List <String> columnNameList = new ArrayList <String>();
List <String> columnTypeList = new ArrayList <String>();
List <Integer> columnLengthList = new ArrayList <Integer>();
String result = "";
columnNameList.add("Id");
columnNameList.add("Name");
columnNameList.add("Address");
columnTypeList.add("char");
columnTypeList.add("varchar");
columnTypeList.add("varchar");
columnLengthList.add(18);
columnLengthList.add(50);
columnLengthList.add(10000);
outermostloop: for (String name : columnNameList )
{
outerloop: for (String type : columnTypeList)
{
loop: for (int len : columnLengthList)
{
if(len > 0 && (!type.equalsIgnoreCase("int") && !type.equalsIgnoreCase("datetime") && !type.equalsIgnoreCase("datetime2")))
{
if(len > 8000 && !(name.equalsIgnoreCase("Id")) && (type.equalsIgnoreCase("varchar")))
{
result = name + type + "(max) ";
System.out.println("if len > 8000 && name not id and type is varchar " + result);
// O/P expected : Address varchar(max)
}
else
{
String finalres = name + type + "("+ len +") ";
System.out.println("No conversion " + finalres);
/* O/P expected : Id char(18)
Name varchar(50)
*/
}
}
break outerloop;
}
}
}
But what I am getting with above logic :
No conversion Id char (18)
No conversion Name char (18)
No conversion Address char (18)
You have to iterate over the elements of the List until you find an element larger than 8000.
With Streams you can write it with:
if (columnLengthList.stream().anyMatch(i -> i > 8000)) {
} else {
}
This might help:
public static void main(String[] args) throws Exception {
ArrayList<Integer> ar1 = new ArrayList<>();
ar1.add(1);
ar1.add(2);
ar1.add(3);
ar1.add(4);
ar1.add(5);
int particular_value = 3;
for (int i : ar1) {
if (i > particular_value)
System.out.println("Value " + i + " is greater than " + particular_value);
}
}
You have to iterate over the list. Either using streams or an extended for loop or a general for loop.
For ex:
List <Integer> columnLengthList = new ArrayList <Integer>();
columnLengthList.add(8001);
columnLengthList.add(7000);
for (Integer eachElement: columnLengthList) {
if (eachElement > 8000) {
// run these
} else {
// run these
}
}
The input is meant to appear like this, example.
\n
Kazan R
\n
6789
\n
Nzk462
\n
However the output I receive looks like this
kzn462nullnzk
Why is this? and How can i solve it?
private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {
secondname = JOptionPane.showInputDialog("Enter your surname:");
firstname = JOptionPane.showInputDialog("Enter your firstname:");
idno = JOptionPane.showInputDialog("Enter your idno:");
nametag = firstname.substring(0, 1);
initials = secondname + " " + nametag;
int randnum;
do {
randnum = (int) (Math.random() * 900) + 100;
} while (randnum % 2 != 0);
code = secondname.replaceAll("[aeiou || AEIOU](?!\\b)", "")+randnum ;
txaDisplay.append(initials + '\n' + idno.substring(6,10) + '\n' + code);
int length = secondname.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + secondname.charAt(i);
}
String end = reverse + code;
txaDisplay.append( reverse);
Why don't you use
new StringBuilder(secondname).reverse().toString()
to reverse your String? It's better, simple and more maintanable.
Get the character array from your source string
Create a new char array of same length
Start iterating from 0 to (sourceStringLength-1)
In each iteration, get the last character
from the end in your source array and populate in your new array
Create a new string from this new array
String source = "abcdefg";
char[] chars = source.toCharArray();
char[] reverseChars = new char[source.length()];
int len = source.length();
for(int i= 0; i < len; i++){
reverseChars[i] = chars[len-1-i];
}
String reverse = new String(reverseChars);
System.out.println(reverse);
Since You don't want to use StringBuilder/StringBuffer.
Try this
String reversedString="";
for(int i=inputString.length-1;i>=0;){
reversedString+=inputString.charAt(i--);
}
I think the problem is your definition of reverse, maybe you have something like:
String reverse;
Then you don't initialize your "reverse" so when your program makes the first concatenation in your loop, it looks like this:
reverse = null + secondname.charAt(i);
The null value is converted to a string so it can be visible in the output.
I hope this information helps you.
Good Luck.
I have a String named listOfItemsBanned, and an ArrayList named itemsBanned.
Let's say the ArrayList itemsBanned contains 3 things: TNT, EnderPearl, and Sand.
I would want the String to be "TNT, EnderPearl, Sand".
And when something is removed from itemsBanned, it would remove it from the string, too.
So.. I want to be able to get every item included in an ArrayList and put it into one String with each item separated by commas.
You need only one line:
String listOfItemsBanned = itemsBanned.toString().replaceAll("^.|.$", "");
toString() of List produces a CSV of the elements, but wrapped in [ and ]. The call to replaceAll() removes the first and last characters to leave just the elements.
You could do this:
String listOfItemsBanned = "";
for(int i = 0; i < itemsBanned.size(); i++){ //loop threw contents of itemsBanned (List<String>)
String s = itemsBanned.get(i); //get the string in itemsBanned (i)
listOfItemsBanned = listOfItemsBanned + "," + s; //add s to listOfItemsBanned
}
Now, if you would like to get all of the items that are banned from the string listOfItemsBanned, you could do:
String[] s = listOfItemsBanned.split(",");
//start the for loop at 1 because when saved it will be ",TnT,Sand,Enderpearl", notice the extra , in the begining
for(int i = 1; i < s.size(); i++){ //loop threw all of the items banned.
String itmBanned = s[i];
}
You could now do anything with itmBanned, like convert it to a Material:
Material m = Material.getMaterial(itmBanned);
So, you could do something like this for a remove method:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.remove(type); //remove 'type' from the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
and for adding:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.add(type); //add 'type' to the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
then you could check if the player is using a banned item, and cancel the event if they do, an example if they're using a banned block, like sand or TnT would be:
#EventHandler
public void playerInteract(PlayerInteractEvent e){
if(e.getAction.equals(Action.RIGHT_CLICK_AIR) || e.getAction.equals(Action.RIGHT_CLICK_BLOCK){
//the user has right-clicked
Material m = e.getItemInHand().getType(); //get the item in the user's hand
if(m != null){ //check that it's not null
if(listOfItemsBanned.contains(m.getName()){ //if listOfItemsBanned has the name of the item in the player's hand in it
e.setCanceled(true); //cancel the block place
}
}
}
}
Imports:
import java.util.Arrays;
import java.util.List;
Code:
public static void main(String args[]) {
String[] listOfItemsBanned = { "TNT", "EnderPearl", "Sand" }; // ArrayList
// of
// banned
// items
String output = ""; // Creates output String
for (int i = 0; i < listOfItemsBanned.length; i++) { // Loops through
// all items in
// the ArrayList
output += listOfItemsBanned[i]; // Adds item to String
if (i != listOfItemsBanned.length - 1) { // If it is not the last
// item in the ArrayList
// add ", "
output += ", ";
}
}
System.out.println(output); // Output String
}
Output:
TNT, EnderPearl, Sand
I need to implement a delete method WITHOUT USING AN ARRAY LIST. I need to use a set of loops to do it. Here is my delete method and add method as well as any other important variables used. Any advice on what is wrong with my code would be great.
EDITED: Changed the comparing of references to values. Seems to work repeatedly.
final int MAX_DEVICES = 5;
// Array of devices
private Device list[] = new Device[MAX_DEVICES];
// Number of Devices currently in the list
// "Valid" Devices are stored in cells 0 - (numDevices - 1)
private int numDevices = 0;
Scanner stdin; // read from stdin
private void Add()
{
String thisName;
int numThisRead;
float thisInitVal;
thisName = stdin.next();
numThisRead = stdin.nextInt();
thisInitVal = stdin.nextFloat();
if(numDevices > MAX_DEVICES)
System.out.println("The List was full. " + thisName +
" was not added to the list.");
else
{
Device myDevice = new Device(thisName, numThisRead, thisInitVal);
list[numDevices] = myDevice;
numDevices ++;
System.out.println(thisName + " device has been added to the list.");
}
}
private void Delete() //ASK QUESTION
{
String thisDelete;
thisDelete = stdin.next();
for(int i = 0; i < MAX_DEVICES; ++i)
{
if(list[i].getName().equals(thisDelete)) //if you find the name
{
System.out.println(list[i].getName() + " was deleted from the "
+ "list.");
for(int j = i; j < numDevices - 1; j++)
list[j] = list[j + 1];
numDevices--;
return;
}
}
System.out.println(thisDelete + " not deleted. It is not in the list.");
}
If you need to avoid using data type List, you can place the objects in the array. Then you can declare an array one element smaller than the current array and copy all the elements, except for the one you want deleted, over into the new array. Then return the new array.