I am using this code, and for some reason, I'm getting a No Such Element Exception...
numCompanies is being imported from the keyboard and is showing up right and portfolio is an array with [numCompanies][4].
Can anyone figure out why?
for(int i = 0; i < numCompanies; i++)
{
System.out.print("Stock #" + (i+1) + ": ");
String stockData = kbReader.nextLine();
System.out.print("\n\n hi" + stockData);
Scanner stockLine = new Scanner(stockData);
for(int j = 0; j < 4; j++)
{
portfolio[i][j] = stockLine.next();
}
}
I have not tested this but probably stockLine.next(); is called even though there is no element left. So maybe this could help:
for(int j = 0; j < 4; j++)
{
if( stockLine.hasNext() ) {
portfolio[i][j] = stockLine.next();
}
else
{
portfolio[i][j] = 0; // or whatever you want it to be by default
}
}
This will solve the error message but not the fault.
You're passing a single string to a Scanner object, but I would say there's a better way of doing this.
If you want to simply read in the input for each value in the string, separated by spaces, then use split():
String stockData = kbReader.nextLine();
String[] data = stockData.split(" ");
if (data.length != 4) {
System.err.println("Bad data value found!");
} else {
//run your loop
}
Related
This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)
this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code
I have two ArrayLists: phNumbers and pinNumbers. Both with the same amount of elements. I am trying to check if a given value is in the first phNumbers, and if it is, at what index of the phNumbers ArrayList was that value found. I then wish to check if a second value is in the pinNums ArrayList at the index previously identified.
Here is my code so at the moment:
for(int i = 0; i < phNumbers.size() && i < pinNums.size(); i++){
index1 = phNumbers.indexOf(i);
index2 = phNumbers.indexOf(i);
index3 = pinNums.indexOf(i);
if(phNumbers.get(i).equals(details[1].trim()) && pinNums.get(index1+1).equals(details[2].trim())){
//send response1
}
else if(phNumbers.get(i).equals(details[1].trim()) && !pinNums.get(index2+1).equals(details[2].trim())){
//send response2
}
else if(pinNums.get(i).equals(details[2].trim()) && !phNumbers.get(index3+1).equals(details[1].trim())){
//Send response3
}
else{
//send response4
}
}
The issue I am having is that it is not working for any elements beyond the first, so I'm assuming it's an issue with my for loop. Could anyone offer some assistance?
So, First if you have a phNumber arraylist and one string of phnumber then try this
ArrayList<String> phNumbers = new ArrayList<>();
phNumbers.add("aaa");
phNumbers.add("bbb");
phNumbers.add("ccc");
phNumbers.add("ddd");
ArrayList<String> pinNums = new ArrayList<>();
pinNums.add("ddd");
pinNums.add("bbb");
pinNums.add("ccc");
pinNums.add("aaa");
for (int i = 0; i < phNumbers.size(); i++) {
for (int j = i; j < pinNums.size(); j++) {
if (phNumbers.get(i).equalsIgnoreCase(pinNums.get(j))) {
Log.e("mye", "phone number and pin number match on this index" + i + "for phnumber and index " + j + "for pin number");
}
}
}
if you want to break after some point then you need to break for loop.
its ok or you want anything else?
I'm creating an array that will sort arrayString[10][2] and then display the results to the user using JOptionPane. The length of the 2D array is irrelevant, just note that it will not be completely populated resulting in nulls. When I display the information to the user I want to exclude the nulls. Currently I have used a variable "isNull" to make this work but I know it is inefficient and am looking for the proper way to accomplish this.
The Array with two rows of data
String arrayString[][] = new String[10][2];
arrayString[0][0] = "Doe";
arrayString[0][1] = "John";
arrayString[1][0] = "Doe";
arrayString[1][1] = "Jane";
The actual program logic
String output = "";
int isNull = 0;
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][j] == null )
{
isNull = 1;
break;
}
else
output += arrayString[i][j] + " ";
isNull = 0;
}
if(isNull == 1)
break;
else
output += " \n";
}
JOptionPane.showMessageDialog(null,output,"Results",JOptionPane.INFORMATION_MESSAGE);
Thanks for all the help guys, I wen't back through my code and reevaluated it and got an answered I'm satisfied with on my own. Thanks for the responses though.
Solved
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][0] == null)
break;
else
output += arrayString[i][j] + " ";
}
if ( arrayString[i][0] == null)
break;
else
output += " \n";
}
// Make a List of all anagram groups above size threshold.
List<List<String>> winners = new ArrayList<List<String>>();
for (List<String> l : m.values())
if (l.size() >= minGroupSize)
winners.add(l);
// Sort anagram groups according to size
Collections.sort(winners, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
return o2.size() - o1.size();
}});
// Print anagram groups.
for (List<String> l : winners)
System.out.println(l.size() + ": " + l);
Look at this post more accurate:
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html#sorting
I am trying to iterate a string that contains the users inputed values. I want to validate that the user only enters 4 characters and that all of them are between 1 and 4. For example, prompts the user to enter 4 values using commas, therefore they can only enter 1,2,3,4. If they enter anything else, then they will be asked again. I have included the section of my code where I am trying to perform the validation. I am also experiencing an unreachable code error which does not make sense to me. This takes place after I close the while (true) loop.
//Entering by ROWS
//This is for a 4x4 board size using rows
if (dataSelection == 1) {
if (boardSize == 1) {
int row = 1;
while (row < 5)
{
String row1Values4x4 = "-1";
while (true)
{
Scanner firstRow4x4 = new Scanner(System.in);
System.out.println("Please enter four values using commas for row " + row); //this needs to loop
row1Values4x4 = firstRow4x4.next();
row1Values4x4 = row1Values4x4.replaceAll(" ",""); //this is in case user enters numbers with spaces
for (int i = 0; i < row1Values4x4.length(); i++) {
char c = row1Values4x4.charAt(i);
if (row1Values4x4.length() == 7 && c == 48) //I entered 48 in order to test if it is using ascii value (48 = 0) {
break;
}
}
} //I think I need to include another break in order to escape the second loop?
String strArray[] = row1Values4x4.split(","); //This is where I get an unreachable code error
int arraySidesInteger[] = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
arraySidesInteger[i] = Integer.parseInt(strArray[i]);
}
fourArray[row-1] = arraySidesInteger;
for (int i = 0; i < fourArray.length; i++) {
for (int j = 0; j < fourArray.length; j++)
System.out.print(fourArray[i][j] + " ");
System.out.println();
}
row++;
}
Please let me know if there
Your comment is right; you need a second break in there. The break that exists only breaks out of the for loop, but not the while loop.
Perhaps instead of
while (true)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
break;
}
}
}
you could try something like
boolean done = false;
while (!done)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
done = true;
break;
}
}
}
Why not use the split method in strings
String s = userInput;
String[] inputArray = s.split(",");
for(int i = 0; i < inputArray.length; i++){
// check if the character is correct here
}