So this is a snippet of code for a uni project im doing fairly new to java so excuse any poor code. One of the restrictions is that the code mustn't have errors on exit / cancel. So i understand that the cancel button on JOptionPane.showInputDialog returns null but it seems the section of 'parts = temp.split(" ")' is for reasons unknown to me blocking input from being null? When i get rid of parts=temp.split() there is no exception thrown when cancel button is selected but then obviously the for loop doesn't work.So what i need to do is for there to be no exception or error's produced upon cancel.Any help would be appreciated! :)
** Edit** We're also forbidden to use catch, try or break any while loops.Must exit with a true / false.
while (X == true && flag == true) {
input = JOptionPane.showInputDialog("Tell me more about " + topics[z]);
String temp = input;
if (input != null) {
flag = true;
}
else if (input == null) {
flag = false;
}
parts = temp.split(" ");
for (int i = 0; i < parts.length; i++) {
for (int x = 0; x < topics.length; x++) {
if (parts[i].equals(topics[x])) {
cut = parts[i];
break;
}
}
}
for (int i = 0; i < topics.length; i++) {
if (cut.equals(topics[i])) {
z = i;
break;
}
}
input = cut;
System.out.print(cut);
System.out.println(z);
X = Arrays.asList(topics[z]).contains(input);
System.out.println(X);
}
You need to write parts = temp.split(" "); inside if (input != null) and make sure parts is initialized before this as well; otherwise you'll get NPE in line parts.length as well.
I'll assume topics is not null:
while (X == true && flag == true) {
input = JOptionPane.showInputDialog("Tell me more about " + topics[z]);
String temp = input;
parts = new String[initialArraySize];
if (input != null) {
parts = temp.split(" ");
flag = true;
}
else if (input == null) {
flag = false;
}
for (int i = 0; i < parts.length; i++) {
for (int x = 0; x < topics.length; x++) {
if (parts[i].equals(topics[x])) {
cut = parts[i];
break;
}
}
}
for (int i = 0; i < topics.length; i++) {
if (cut.equals(topics[i])) {
z = i;
break;
}
}
input = cut;
System.out.print(cut);
System.out.println(z);
X = Arrays.asList(topics[z]).contains(input);
System.out.println(X);
}
Related
I am a beginner on java.
Why it always show not found?
and how exactly make a not found string value on array?
String[] array = new String[10];
String b = "5";
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
}
}
Your second for loop terminates on i = 0 when you call System.exit(0); (the program actually terminates overall when you call that).
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
Suggest changing the logic to break from the loop when the match has been found.
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
break;
}
}
Okay i've been figure it out.
Thanks for the advice.
Just make "not found" statement outside the loop.
String[] array = new String[10];
String b = "10";
boolean c = false;
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
c = true;
}
}
if (c == true){
System.out.println("not found");
}
}
I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.
i'm working on an application on deterministic finite automata but there's a problem in algorithm, all the details will be set from user's input. it becomes problem if user inputs details like following
totalStates = 3 //user input
initialState = 1 //user input
finalState = 3 //user input
//transitions created in linked-list
//contains three data members(prevState(int), transition symbol(String), nextState(int))
2->b->1 //user input
1->a->2 //user input
2->b->3 //user input
string = ab
this is a valid string for this automata but not according to my algorithm, there's problem in algo that it changes the states according to transitions indexes. like
for 'a' it works good and change the state from 1 to 2
for 'b' it choose the transition from 2 to 1 not 2 to 3
because 2->b->1 is created before 2->b->3
how to solve this using linked-list( for transitions) and String(for string input) in java. Thanks
complete code is
public boolean match() {
s = str;
current = FiniteAutomata.startState;
for (int t = 0; t < str.length(); t++) {
curFlag = false;
list2 = originalList.head;
while (list2 != null) {
if (current == list2.initialState) {
for (int i = 0; i < s.length(); i++) {
String s2 = delL(s.toCharArray(), i);
if (s2.equals(list2.transitionString)) {
current = list2.finalState;
curFlag = true;
s = delF(s.toCharArray(), i);
}
}
}
if (curFlag) {
break;
}
list2 = list2.next;
}
}
boolean flag = false;
if (s.equals("")) {
for (int i = 0; i < FiniteAutomata.finalStates.length; i++) {
if (current == FiniteAutomata.finalStates[i]) {
flag = true;
}
}
}
if (flag) {
return true;
} else {
return false;
}
}
String delF(char[] temp, int c) {
String s = "";
for (int i = c + 1; i < temp.length; i++) {
s = s + temp[i];
}
return s;
}
String delL(char[] temp, int c) {
String s = "";
for (int i = 0; i <= c; i++) {
s = s + temp[i];
}
return s;
}
I want my code to loop through an array and only give the user an option to delete a student only if there are values in the array. If all the array values are null then I want it to print out a message. The problem is that my message is printing out multiple times for each null element in the array.
My code:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (i = studentChoice + 1;i < studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(i = studentChoice + 1;i < 9;i++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[i-1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for(int y = 0;y < 3;y++) {
studentMarksArray[9][y] = 0;
}
} else {
System.out.println("There are no students stored");
}
}
}
The else block runs in each loop iteration. If you want to run it only once at the end, do something like this:
boolean studentFound = false;
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
...
Then after the for:
if (!studentFound) {
System.out.println("There are no students stored");
}
Here is how I would determine if all the elements are null. The reason yours prints it out for each null element is that the print statement is inside the for loop.
boolean allNull = true; // default is that everything is null
for(int i = 0; i < studentNamesArray.length; i++) { // iterate through entire array
if(studentNamesArray[i] != null) { // if even 1 of them is not null
allNull = false; // set allNull to false
break; // and break out of the for loop
}
}
if(allNull) System.out.println("There are no students stored!");
I suggest to use 'boolean' variable, lets name it 'flag'. Initialize it as 'false'. If you found not null element in array, when set 'flag = true'. After 'for' loop check 'if (!flag) System.out.println ("There are no students.");'.
In your for loops, you use the same variable i, in which it overrides the original variable used in the for loop.
Try something like this:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (int j = studentChoice + 1;j < studentNamesArray.length; j++) {
studentNamesArray[j-1] = studentNamesArray[j];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(int k = studentChoice + 1;k < 9;k++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[k-1][y] = studentMarksArray[k][y];
}
}
markArrayCount = markArrayCount - 1;
for(int z = 0;z < 3;z++) {
studentMarksArray[9][z] = 0;
}
} else {
System.out.println("hi");
}
}
}
Although, I am not sure what you are trying to print out, I made adjustments to the other variable names based on my intuition; the result might not be exactly as resulted, but I am sure you can make further adjustments with the variable names so that you are not over-riding each other and causing excessive loops.
This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
Right now you would be getting the same output if your input was -++
You never parse for the order or a, b, c and d. You always assume the order a->b->c->d.
So d-c+a+b will be: a-b+c+d which is consistent with the output you provided(100-5+10+13 = 118)
OP's CODE
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
/OP'S CODE
In this loop, when k is not an operator, you should be reading which letter it is, and store the order in which the letters appeared. Or build some other kind of mapping. In any case you can't just ignore non-operator characters because they are part of the input.
Let's debug this a little, add a few system outs...
this is what you would see for each step
100.0 - 5.0
95.0 + 10.0
105.0 + 13.0
118.0
your value array is {100,5,10,13} and your operator array is {-,+,+}
you have not mapped a = 100, b = 5, c= 10, d = 13, unless you map those then parse the operands using the mapping based on the non operand input keys, it is not going to work.
So, if I were to use the character's int values, I would be able to translate it this way.
import java.io.*;
public class TestC {
public static void main(String[] args) {
int i = 0, j = 0;
double result, values[] = new double[4];
char k, operatorsAndOperands[] = new char[3];
for (i = 0; i <= 2; i++)
operatorsAndOperands[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)) {
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
for (int l = 0; l < values.length; l++) {
System.out.println(values[l]);
}
} catch (FileNotFoundException e) {
System.err.println(e);
return;
} catch (IOException f) {
System.out.println(f);
return;
}
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine().toUpperCase();
} catch (IOException f) {
System.out.println(f);
return;
}
if(InputText.length() > 0){
operatorsAndOperands = new char[InputText.length()];
} else {
System.out.println("No Operations specified");
return;
}
for (i = 0; i < InputText.length(); i++) {
k = InputText.charAt(i);
operatorsAndOperands[j++] = k;
}
result = 0;
for (i = 0; i < operatorsAndOperands.length; i++) {
System.out.println(operatorsAndOperands[i] + " " + (int)operatorsAndOperands[i]);
if(i+1<operatorsAndOperands.length)
System.out.println(operatorsAndOperands[i+1]);
switch(operatorsAndOperands[i]){
case '+':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result+=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
case '-':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result-=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
default:
result = values[(int)operatorsAndOperands[i] - (int)'A'];
break;
};
System.out.println(result);
}
System.out.println(result);
}
}