Arrays not matching correctly - java

userAnswer[] holds the string of the answer the user types in and is comparing it to answers[] to see if they match up and then spits out correct or wrong. j is equal to the question number. So if j was question 6, answers[j] should refer to answers[6] right?
Then userAnswer[6] should compare to answers[6] and match if its correct. But its giving me wrong answers and displaying the answer I typed as correct.
int abc, loopCount = 100;
int j = quesNum, overValue, forLoop = 100;
for (int loop = 1; loop < loopCount; loop++)
{
aa = r.nextInt(10+1);
abc = (int) aa;
String[] userAnswer = new String[x];
JOptionPane.showMessageDialog(null,abc);
if(abc < x)
{
userAnswer[j] = JOptionPane.showInputDialog(null,"Question "+quesNum+"\n"+questions[abc]+"\n\nA: "+a[abc]+"\nB: "+b[abc]+"\nC: "+c[abc]+"\nD: "+d[abc]);
if(userAnswer[j].equals(answers[j]))
{
JOptionPane.showMessageDialog(null,"Correct. \nThe Correct Answer is "+answers[abc]);
}
else
{
JOptionPane.showMessageDialog(null,"Wrong. \n The Correct Answer is "+answers[abc]);
}//else
}//if
}//for

Your indices are named poorly, and you mix them up yourself. You want to check answers[abc] and not answers[j] against userAnswer[j].

For question 6 you need answers[5] because arrays are indexed starting from 0. 0 would be question 1, 1 would be question 2, etc.

Your userAnswer array is scoped by the for loop. If you mean to use the values outside of this loop, you need to move the defintion outside of the loop. Otherwise, you can just use one answer string as right now you are not accessing the values a second time.

Related

How do you replace multiple words in a string at once in Java?

I am new to Java and am trying to make a program that will take a string 'names' and replace the names of the people mentioned in that string with a nickname from another string 'replacement'. For instance, "John and Robert were on the way to meet Elizabeth" should return "Joe and Bob were on the way to meet Liz".
My issue is that whenever I run my program, I get multiple sentences back with only one name replaced in each (I'm guessing it is creating a new string each time). Is there a way to avoid this and have it all printed in one sentence? Could I use regex on 'replacement' somehow to fix it?
public static string namereplacer(String names, String replacement) {
String[] toreplace = replacement.split("\t|\n");
for (int i = 0; i <= toreplace.length/2; i++) {
if (i % 2 == 0) { //take even values
fixed; += names.replaceAll(toreplace[i+1],toreplace[i]);
}
}
return fixed;
}
public static void main (String[] args) {
namereplacer("John and Robert were on the way to meet Elizabeth", "John\tJoe\nRobert\tBob\nElizabeth\tLiz");
}
I couldn't run the code you have submitted because the variable fixed isn't declared and i suspect the line
fixed; += names.replaceAll(toreplace[i+1],toreplace[i]);
is supposed to be
fixed += names.replaceAll(toreplace[i+1],toreplace[i]);
because that would somewhat explain why you are getting multiple sentences, since you are replacing things multiple times and adding the result to fixed.
That being said I have noticed that when you are replacing the names with
names.replaceAll(toreplace[i+1],toreplace[i]); you should be doing
names.replaceAll(toreplace[i],toreplace[i+1]); since you would like to replace John for Joe, Robert for Bob and Elizabeth for Liz, not the other way around (Joe for John). Basically you want to replace the "even" with the "odd" so if you are selecting the even values of i you you like to replace those with i+1.
Also when iterating the array in the for loop with
for (int i = 0; i <= toreplace.length/2; i++)
you should be doing
for (int i = 0; i <= toreplace.length; i++)
because you want all the "evens" not just half of them, i think you might have switched up yourself a bit here with the evens logic and replacing half...
So to make your code work like you intend to you should replace the following lines:
for (int i = 0; i <= toreplace.length/2; i++) for
for (int i = 0; i <= toreplace.length; i++)
fixed; += names.replaceAll(toreplace[i+1],toreplace[i]); for
fixed = fixed.replaceAll(toreplace[i+1],toreplace[i]);
and also define the variable fixed beforehand Sting fixed = names; so that it has the same value as names.
Furthermore you can also improve your code a little bit:
A for is constituted by three statements for(statement1; statement2; stament3)
statement1 is executed a single time before the code block (what's inside the for)
statement2 defines the condition for executing the code block, the for will run while this statement is true
statement3 is executed everytime after the code block has been executed by the for loop
Generaly you will find and write foor loops like for(i=0; i!=foo; i++) where statement1 is used for variable initialization, statement2 for condition and statement3 for increment, but that doens't mean it is all you can do with it, in reality you can write whatever you want/need in those statements.
In you case you have
for (int i = 0; i <= toreplace.length/2; i++) {
if (i % 2 == 0) { //take even values
fixed; += names.replaceAll(toreplace[i+1],toreplace[i]);
}
}
This means you are iterating over the toreplace array, taking the "evens" and replacing them with the "odds" on the fixed string, however inside the for loop you are selecting only half of the iterations you are making with if (i % 2 == 0) and you don't really need to do that since you can just choose to iterate by 2 instead of iterating all of them and only selecting half of them to do the replacement.
To do this you simply declare for (int i = 0; i != toreplace.length; i+=2) or the long way i=i+2 if you prefer, and you no longer need the if statement because you know you will be iteraing over all the even numbers.
Hope this helped you in some way.
Change the method namereplacer to this
public static String namereplacer(String names, String replacement) {
String[] toreplace = replacement.split("\n");
for(String str: toreplace){
String [] keyValue = str.split("\t");
if(keyValue.length != 2)
continue;
names = names.replaceAll(keyValue[0], keyValue[1]);
}
return names;
}

Shouldn't these two loops produce the same result?

I was solving a programming problem where you get an input and you have to add every number from 1 - input to the input for example lets say the input
is 5 :5+4+3+2+1 = 15.
To solve this I tried these two for loops below.
//This loop worked for most inputs
int input = 12 ;
for(int i = input - 1; i > 0; i--) {
input += i;
}
System.out.println(input);
//This just produced a negative number
int input2 = 12;
for(int i = 1; i < input2;i++){
input2 += i;
}
System.out.println(input2);
Only one loop worked although the seem like they should produce the same result can anyone explain?
Errors are pretty nicely defined in previous answers, I'm just going to add the following:
This could also be solved using ArrayList and summing its members with loop, but it would be an overkill.
That gives you ability to remove/change values of the list you iterating through using Java Iterator class.
As I said before, this solution is overkill for such task, but it could be interesting to research.
More of Java Iterator: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

Error in swapping characters in stringbuffer object

i am trying to sort a string in the alphabetical order, however i am facing an error in the line :
sb.charAt(j)=sb.charAt(j+1);
where the compiler shows an error as expected variable; found value
the rest of the code is as follows :
import java.util.Scanner;
class a
{
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuffer sb = new StringBuffer();
sb.append(s);
for(int i = 0; i< s.length(); i++)
{
for(int j = 0; j<s.length(); j++)
{
if(s.charAt(j)>s.charAt(j+1)){
char temp = s.charAt(j);
sb.charAt(j)=sb.charAt(j+1);
sb.charAt(j+1)=temp;
}
}
}}}
kindly help me out as i'm a beginner and i cannot figure out why this issue is occurring , thank you .
This looks like a homework assignment where the goal is to sort the characters of a text being entered, so if you enter gfedbca the result should be abcdefg.
You already got a comment telling you what the problem is: StringBuffer#charAt() is not returning a reference to StringBuffer's internal array that you can change the value of. Dependent on the actual assignment you can call StringBuffers setCharAt method or you can go another approach by converting the text to sort to a char array and do the sorting in there. There are actually helper-classes in the JVM, that do that for you, have a look e.g. at the class java.util.Arrays
As already answered by many, the issue is in charAt(index) you are using, as this returns the character at the given index rather than setting a char at the index position.
My answer is to divert your approach of sorting. For simpler solutions, where smaller data sets (like your problem) are used, you should use the predefined sorting algorithms, like Insertion Sort
You may get help for the algo from here: http://www.geeksforgeeks.org/insertion-sort/
StringBuffer's charAt returns just the value of the char at the index, if you want to swap two chars you need to use setter for that, so you possible want to do somtehing like:
for(int j = 0; j < s.length() - 1; j++) {
if(s.charAt(j) > s.charAt(j + 1)) {
char temp = s.charAt(j);
sb.setCharAt(j, sb.charAt(j + 1));
sb.setCharAt(j + 1, temp);
}
}
This method can only return values and can not set values, I guess you might want to use this method:
setCharAt()
It can meet your requirement

Why isn't this code reversing user inputted text?

System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);
String x = sc1.nextLine();//user input
for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}
In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
System.out.print(x.substring(i, i+1));
}
substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
System.out.print(x.charAt(i));
}
As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
System.out.print(x.charAt(i));
}

Wrong output from a while loop using indexOf [duplicate]

This question already has answers here:
While loop doesn't run a indexOf search
(4 answers)
Closed 8 years ago.
I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 2 for my "appearance" variable, which should store how many times "ea" appears in wordTwo. It should return 3.
I've tried messing with variable initializations, and trying to think of the math differently, but I'm pretty much out of ideas.
Here's the relevant code section:
int wordTwoLength = wordTwo.length();
System.out.println(wordTwoLength);
while (wordTwoLength > 0)
{
positionCount = wordTwo.indexOf(wordOne, positionCount);
appearances++;
wordTwoLength = (wordTwoLength - positionCount);
}
System.out.println(appearances);
Thanks!
Edit: I forgot to add that I tried other test inputs and got crazy outputs. It would return numbers way higher than expected for some, and lower for others.
So now the problem is that .indexOf still returns the true index of "ea" in wordTwo - it doesn't take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.
The index of the first instance of "ea" in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you'll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you'll exit the while loop, with appearances being 2.
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
appearances ++;
Try this simpler code:
class Demo{
public static void main(String[] args){
String wordOne = "ea";
String wordTwo = "Ilikedthebestontheeastbeachleast";
String[] arr = wordTwo.split(wordOne);
int cnt = arr.length - 1;
System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo);
}
}
You can simplify your above work by "Converting String to Character array".Because it will be more Efficient(I think).I have provided a sample code here,
String wordOne="Ilikedthebestontheeastbeachleast";
String wordTwo="ea";
int count=0;
char[] arrayOne=wordOne.toCharArray();
char [] arrayTwo=wordTwo.toCharArray();
for(int i=0;i<=((arrayOne.length)-1);i++)
{
if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1])
count+=1;
}
System.out.println("Pattern found "+count+" times.");
This will suits your need but using For loop.

Categories