One of the practice problems our instructor gave us for an intro to JAVA class is giving me an error for creating an infinite loop. I would like to know how to get the same output that I am getting (test output is shown in the screenshot) without this error.
The instructions on the assignment are as follows:
Write a method named flipLines that accepts as its parameter a Scanner for an input file and that writes to the console the same file's contents with successive pairs of lines reversed in order. The program should print the first pair of lines in reverse order, then the second pair in reverse order, then the third pair in reverse order, and so on. An input file can have an odd number of lines in which case the last line is printed in its original position.
This image is a screenshot of the error along with my code on the website.
This is my first post so hopefully I formatted this correctly.
Just in case, here's my code again:
public static void flipLines(Scanner input)
{
int x = 0;
String evenLine = "";
String oddLine = "";
boolean value = true;
while (value = true)
{
if (input.hasNextLine())
{
x++;
}
else
{
value = false;
}
}
for (int i = 0; i < x; i++)
{
if (i < x && i % 2 == 0)
{
evenLine = input.nextLine();
System.out.println(evenLine);
}
else
{
continue;
}
}
for (int j = 0; j < x; j++)
{
if (j < x && j % 2 != 0)
{
oddLine = input.nextLine();
System.out.println(oddLine);
}
else
{
continue;
}
}
}
change your assignment
while (value = true)
to comparison
while (value == true)
value = true assigns true to value and returns true, which means the loop will never end.
EDIT :
In addition, input.hasNextLine() will always return true since you are not reading any line until after the while loop, which is why that loop never ends.
You can't find the number of input lines without actually reading the lines.
Your for loops also don't do what you think they should do. Just because you skip an iteration of the for loop doesn't mean that you skip a row of the input.
What you need is a single loop that reads two lines (assuming there are two lines available) in each iteration and prints them in reversed order.
String line1 = null;
while (input.hasNextLine()) {
line1 = input.nextLine();
if (input.hasNextLine()) {
String line2 = input.nextLine();
System.out.println(line2);
System.out.println(line1);
line1 = null;
}
}
if (line1 != null)
System.out.println(line1);
Related
I'm trying to get all of the indexes of a Boolean array to be printed out where its element is true. The end goal is to be able to find a prime number of the indexes (where I change each index number that isn't prime to false in the array) then print out only what is left of the prime numbers of the indexes of the array.
The very first step I'm just trying to do is at least to get some integer index to print out, but nothing seems to be working and I don't know what is wrong.
public class PriNum{
private boolean[] array;
public PriNum(int max){
if (max > 2){ //I don't have any problems with this if statement
throw new IllegalArgumentException();
}
else{
array = new boolean[max];
for(int i = 0; i < max; i++){
if(i == 0 || i == 1){ //Automatically makes 0 and 1 false
//because they are not prime
array[i] = false;
}
else{
array[i] = true;
}
}
toString(); //I know for sure the code gets to here
//because it prints out a string I have
// there, but not the index
}
}
public String toString(){
String s = "test"; //this only prints test so I can see if
//the code gets here, otherwise it would just be ""
for (int i = 0; i < array.length; i++){
if(array[i] == true){
s = s + i; //Initially I tried to have the indexes returned
//to be printed and separated by a comma,
//but nothing comes out at all, save for "test"
}
}
return s;
}
}
EDIT: Included is the driver class that's requesting the print of the class PriNum
class Driver{
public static void main(String [] args){
PriNum theprime = null;
try{
theprime = new PriNum(50);
}
catch (IllegalArgumentException oops){
System.out.println("Max must be at least 2.");
}
System.out.println(theprime);
}
}
I tried running this, and the first change that needs to happen is to set this argument:
if(max < 2)
Then, if I'm reading this correctly: 0 and 1 are false. Every index after that is true. The output is fine as I see it. Just all the numbers crunched as a continuous list.
To get a better output, put a space between indexes:
if(array[i] == true){
s = s + " " + i;
}
You may even just output to screen directly as
if(array[i])
System.out.print( i );
numbers is initialized without declaration, array is declared but not initialized anywhere in your code. You have also a syntax error after array[i] = true, should be curly brace...
Actually this is my code :
inputStream = new FileInputStream(file);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(line.contains("blablbal") {
// **take the next five line and put them inside string or something**
}
}
Is it possible to take the next five lines and put them inside string object?
And if there is another occurrence of the condition within these 5 lines how to treat that case?
Any idea?
Definitely you can. Actually the only thing you have to do is to invoke a method doWhatYouWantToDoInCaseOfYourDesire
Do you want to read 5 lines below the given? ok - just create a method that contains a check for a your's condition, contains a counter inside and loop inthere.
But the question is what are you going to do if there is another occurence of your condition within these 5 lines?
I believe it's not enough description for this case
Try with below code:-
String[] lines = new String[20];
//if you want to store more lines increase the size of the array
int j = 0;
//manage below while loop condition j < 20 based on array size and change the
//number from 20 to that number. For example if array size 50 make j < 50
while (sc.hasNextLine() && j < 20) {
String line = sc.nextLine();
if(line.contains("blablbal") {
int i = 0;
while(sc.hasNextLine() && i < 5){
line = sc.nextLine();
if(line.contains("blablbal") {
continue;
}
lines[j++] = line;
i++;
if ( j >= 20 )//change this according to the size of array as well
break;
}
}
I am writing a program that reads a text file which contains match results, and then should output them in a table. I have a While loop within a While loop:
Scanner fileread1 = new Scanner(new File("demo.txt"));
int x = 0;
int y = 22;
int i = 0;
while (x <= y) {
while (fileread1.hasNext()) {
fileinput = fileread1.nextLine(); // this reads the next line of
// from the file
String line = fileinput;
String[] split = line.split(":");
boolean result = false;
int homescore1 = 0;
int awayscore1 = 0;
int goalsscored = 0;
boolean att = false;
boolean htt = false;
int atscore = 0;
int htscore = 0;
// When the text line is read, it is then split into four sections.
if (split.length == 4) {
// String text = line.trim();
String userteam = userteaminput;
String hometeam = split[0].trim();
String awayteam = split[1].trim();
String home_score = split[2].trim();
String away_score = split[3].trim();
// this is a test to try convert the goals string into a
// integer. If this fails, the result is not
// not valid and does not get outputted to the console.
try {
homescore1 = Integer.parseInt(home_score);
awayscore1 = Integer.parseInt(away_score);
result = true;
}
catch (NumberFormatException exception) {
// if the try is not able to convert, this will run
errors++;
}
if (userteam.equals(Teams.get(i))) {
if (awayteam.equalsIgnoreCase(userteam)) {
att = true;
games++;
goalsfor = goalsfor + awayscore1;
goalsagainst = goalsagainst + homescore1;
}
if (att == true && awayscore1 > homescore1) {
atwc++;
gameswon++;
}
else if (att == true && awayscore1 < homescore1) {
htwc++;
gameslost++;
}
else if (att == true && awayscore1 == homescore1) {
gamesdrawn++;
}
if (hometeam.equalsIgnoreCase(userteam)) {
htt = true;
totaluser++;
games++;
goalsfor = goalsfor + homescore1;
goalsagainst = goalsagainst + awayscore1;
}
if (htt == true && homescore1 > awayscore1) {
atwc++;
gameswon++;
}
else if (htt == true && homescore1 < awayscore1) {
htwc++;
gameslost++;
}
else if (htt == true && awayscore1 == homescore1) {
gamesdrawn++;
}
}
}
else {
errors++;
}
}
// ********************************************************************
// Leeds IF Statement
// ********************************************************************
if (Rhinos.equals(Teams.get(i)) {
Rhinos.goalsfor = Rhinos.goalsfor + goalsfor;
Rhinos.gameswon = Rhinos.gameswon + gameswon;
Rhinos.gameslost = Rhinos.gameslost + gameslost;
Rhinos.goalsagainst = Rhinos.goalsagainst;
Rhinos.gamesplayed = Rhinos.gamesplayed + games;
}
else if (Bulls.equals(Teams.get(i)) {
Bulls.goalsfor = Bulls.goalsfor + goalsfor;
Bulls.gameswon = Bulls.gameswon + gameswon;
Bulls.gameslost = Bulls.gameslost + gameslost;
Bulls.goalsagainst = Bulls.goalsagainst;
Bulls.gamesplayed = Bulls.gamesplayed + games;
}
x++;
i++;
goalsfor = 0;
gameswon = 0;
gameslost = 0;
gamesagainst = 0;
}
I know that there are only ever going to be 22 teams that have results in the text file supplied, so the first loop should run for 22 times.
The inner loop, will continue whilst the file provided has a next line. The text file may sometimes have more lines of results then other files. Within this loop, I have a reference to an Array item:
if (userteam.equals(Teams.get(i)))
In the first run, this will refer to 0 in my Array which, for the record, is Leeds Rhinos. Once the inner loop has completed, it then moves onto the outer loop - this deals with the results just recorded. If the current team is Leeds Rhinos, it should then add the values. The i should then have 1 added, so for the next loop, it refers to the index of 1 of the array, not 0. (I have more IF statements here, all identical but refer to other teams) Variables get set back to 0, ready for the next run.
The issue I have, is that i does not seem to have 1 added each time it runs through, so I am only getting results passed through for one team. If I manually specify which array index to look (say 3) it will run through, and the team will have their results successfully recorded.
Is there a way I can get 1 added to i every time it loops? I'm not sure if this is the correct java loop to use, but to me, seemed the most logical. There are some objects not declared here - this is just a snippet of the code, left out the declarations as I know they work, and there's a lot declared.
If you're worried about failed incrementation, it would be better to use a For loop.
Instead of having a while (x < y) and sticking an increment statement somewhere in your code,
a
for (i = 0; i < y; i++) { // do tests here }
loop will guarantee that you always increment and run the test for the next team.
For future reference, when using while loops and incrementing, the incrementation is almost always done at the END of the while loop, and not somewhere in between. The incrementation statement should also almost never be in a conditional statement (which might cause an infinite loop).
Your question is not clear. But let's point out something in the code you provided
1) What is the difference between your if and else if statement? They are checking exact same thing
if (userteam.equals(Teams.get(i)) {
Rhinos.goalsfor = Rhinos.goalsfor + goalsfor;
Rhinos.gameswon = Rhinos.gameswon + gameswon;
Rhinos.gameslost = Rhinos.gameslost + gameslost;
Rhinos.goalsagainst = Rhinos.goalsagainst;
Rhinos.gamesplayed = Rhinos.gamesplayed + games;
}
else if (userteam.equals(Teams.get(i)) {
Bulls.goalsfor = Bulls.goalsfor + goalsfor;
Bulls.gameswon = Bulls.gameswon + gameswon;
Bulls.gameslost = Bulls.gameslost + gameslost;
Bulls.goalsagainst = Bulls.goalsagainst;
Bulls.gamesplayed = Bulls.gamesplayed + games;
}
2) What are you doing with variable x, I don't see anywhere you are increasing it.
3) On very first run, when x<=y, the inner loop will finish reading all lines, so even if you increase the X some point, from second run the inner loop will not execute. As it already finished reading all lines. So no point doing this
Again if you provide some more inside on what you want to accomplish, may be with the sample text file data, that would probably help answering your question.
Thank you.
Your formatting is working against you here; properly indented, your code structure is something like this (note, I had to add in missing closing braces, }, at the end of the code you provided as I assume you just missed them when you copied your code over):
Scanner fileread1 = new Scanner(new File("demo.txt"));
int x = 0;
int y = 22;
int i = 0;
while (x <= y) {
while (fileread1.hasNext()) {
fileinput = fileread1.nextLine(); // this reads the next line of
/* stuff */
if (split.length == 4) {
/* stuff */
x++;
i++;
}
}
}
Your incrementation of x and i is nested within if (split.length == 4) {, meaning that x and i will only be incremented in that specific case and not at the end of each iteration of the inner while loop.
I'm trying to determine if a word entered differs by one character in a text file. I have code that works, but unfortunately only for words that are two characters or less which obviously isn't very useful, and the code itself looks a bit messy. Here's what I have so far:
if(random.length() == word.length()){
for(int i = 0; i < random.length(); i++){
if( (word.charAt(i) == random.charAt(i))){
str += word+"\n";
count++;
}
}
}
With random being the word that was entered by the user, and word being the word to search for in the text file.
If I changed my second if statement to something along the lines of
if( (word.charAt(i) == random.charAt(i)) && (word.charAt(i -1) == random.charAt(i-1)))
and if I change int i to be = 1 instead, I seem to get more of what I'm looking to accomplish, but then my code is searching for only if the first two letters are the same and not if the last two are as well, which it should be doing.
I assume you need a function like this? I just wrote and tested it.
static boolean equals(String word1, String word2, int mistakesAllowed) {
if(word1.equals(word2)) // if word1 equals word2, we can always return true
return true;
if(word1.length() == word2.length()) { // if word1 is as long as word 2
for(int i = 0; i < word1.length(); i++) { // go from first to last character index the words
if(word1.charAt(i) != word2.charAt(i)) { // if this character from word 1 does not equal the character from word 2
mistakesAllowed--; // reduce one mistake allowed
if(mistakesAllowed < 0) { // and if you have more mistakes than allowed
return false; // return false
}
}
}
}
return true;
}
Your code seems to be working to me, you just may be interpreting its results incorrectly.
This may be more obvious:
int count = 0; if(random.length() == word.length()) {
for(int i = 0; i < random.length(); i++)
{
if( (word.charAt(i) != random.charAt(i) ))
{
if(count == 0)
{
System.out.println("Found first difference!");
}
if(count != 0)
{
System.out.println("Strings are more than one letter different!");
}
count++;
}
} }
If you want to check Strings of different lengths, you'll need to delete characters from the longer one until it's the same size as the shorter.
For example:
If String1 = "abc";
and String2 = "zzzabcdef";
You'll need to delete 6 characters from the second string and test for every combination of 6 characters deleted. So you would want to test the strings: def, cde, abc, zab, zza, zzz, zzb, zzc, zzd, zze, zzf, zaf, zae, zad, zac, zab, zza, zzf, zze, ..., ..., on and on, the list is of size 9 choose 6, so it's definitely not optimal or recommended.
You can however, check to see if a string which is one character longer than the other is just the other string with one added letter. To do this, you want a for loop to grab two substring from 0 to i, and from i+1 to the end. This will leave out the ith character, and looping for the size of the string - 1, will give you first the full string, then the string without the first letter, then missing the second letter, and so on. Then test that substring in the same fashion we did above.
Comment if this was not what you're looking for.
EDIT
To see how many words in a file are one letter different than a variable word, you need to loop through the file, getting each word. Then testing if that was string was one letter off. It would be something like this:
String testAgainst = "lookingForWordsOneLetterDifferentThanThisString";
int words = 0;
Scanner scan = new Scanner(fileName);
while(scan.hasNext())
{
String word = scan.next();
if( isOneDifferent(word, testAgainst) )
{
words++;
}
System.out.println("Number of words one letter different: " + words);
}
public boolean isOneDifferent(String word, String testAgainst)
{
if(word.length() != testAgainst.length())
{
return false;
}
int diffs = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) != testAgainst.charAt(i))
{
diffs++;
}
if(diffs > 1)
{
return false;
}
}
if(diffs == 1)
{
return true;
}
else
{
return false;
}
}
EDIT: I now see count wasn't working. I updated the code so now if count is greater than or equal to either word, it'll return "yes". I'm assuming that's the only fix I need to make, so thank you!
When provided with two input phrases, it should check if the letters of one word are all found in the other word, regardless of capitalization. For example, cat and cat would work, as would cat and catt, dogged and do, etc. My code works for some inputs and not others and I can't figure out why. I tried the inputs "cat" and "cat and it works but "moo" and "moo" don't work. I'm also assuming using count might be part of the problem. I also tried using arrays but I figured this might be simpler. I'm not looking for an answer, just an explanation as to why my code is not printing what it should.
Here are my two classes:
import java.util.*;
public class SuperAnTester{
public static void main(String[] args){
System.out.println("Enter two words: ");
Scanner scan = new Scanner(System.in);
String phraseone = scan.nextLine();
String phrasetwo = scan.nextLine();
SuperAnagram x = new SuperAnagram(phraseone, phrasetwo);
x.superAn();
}}
public class SuperAnagram{
private String firstWord;
private String secondWord;
public SuperAnagram(String first, String second){
firstWord = first;
secondWord = second;
}
public void superAn(){
int count = 0;
firstWord.toLowerCase();
secondWord.toLowerCase();
for (int n = 0; n < firstWord.length(); n++){
for (int x = 0; x < secondWord.length(); x++){
if (firstWord.charAt(n) == secondWord.charAt(x)){
count++;
}}}
if (count >= firstWord.length() || count >= secondWord.length()){
System.out.println("Yes");
} else{
System.out.println("No");
}}}
May be the problem is here
firstWord.toLowerCase();
secondWord.toLowerCase();
Change it into
firstWord=firstWord.toLowerCase();
secondWord=secondWord.toLowerCase();
String is immutable class. You have to assign it back to a string to reflect the changes.
Your example a bit a confusing to me. I don't think dog and dogg are usually considered anagram? I believe a prerequisite to be anagram, is that both words should have the same number of character.
Please find an example (assuming you only have ascii characters):
private static boolean isAnagram(String a, String b) {
if (a == null || b == null || a.length() != b.length()) return false;
byte charCount[] = new byte[256];
a = a.toLowerCase();
b = b.toLowerCase();
for (int i = 0 ; i < a.length() ; ++i) {
charCount[a.charAt(i)]++;
}
for (int i = 0; i < b.length() ; ++i) {
int current = --charCount[b.charAt(i)];
if (current < 0) return false;
}
return true;
}
Based on Wikipedia:
An anagram is a type of word play, the result of rearranging the
letters of a word or phrase to produce a new word or phrase, using all
the original letters exactly once; for example orchestra can be
rearranged into carthorse.
This code will not work because what if you have cat and caate ?
c == c OK count = 1
...
a == a OK count = 2
...
a == a OK count = 3
...
t == t OK count = 4
so at the end count = 4;
count != to 3 (cat) and count != 5 (caate)
So you have to take into consideration the redundant characters
The other mistake is that you made the string lower case but you didn't save it. So just assign firstWord.toLowerCase(); to firstWord and secondWord.toLowerCase(); to secondWord.
firstWord = firstWord.toLowerCase();
secondWord = secondWord.toLowerCase();
This is pretty straightforward.
If you take for example 'do' and 'doott' for the letter 'd' count will be incremented once (with the first d of doott), for the letter 'o' it will be incremented twice (withe the first and second o of doott).
So count will be equal to 3 and neither do and doott length is equal to that.
What you can do is use StringUtils.countMatches(yourString, yourchar); for the two strings and check that for the first one the number is lower or equal to the second.