Skip to main content

Posts

Showing posts with the label loops

Filereader null declarations and appending best practice

I want to optimise my file reader function but am not sure if it is best practice to declare the nulls outside of the try loop. Also, is looping and appending chars to a Stringbuffer considered bad practice? I would like to use the exception handling here, but maybe it is better to use another structure? any advice most welcome, thanks. public String readFile(){ File f = null; FileReader fr = null; StringBuffer content = null; try{ f = new File("c:/test.txt"); fr = new FileReader(f); int c; while((c = fr.read()) != -1){ if(content == null){ content = new StringBuffer(); } content.append((char)c); } fr.close(); } catch (Exception e) { throw new RuntimeException("An error occured reading your file"); } return content.toString(); } }

I wrote a "Rock, Paper, Scissor, Shoot” game in one method using Java. I need help looping the program

I am able to loop the program, but each time I input a value it will return 2 values, the user winning and the user losing. I've experimented using multiple methods and creating a new class which was the tester, but had some problems figuring out the logic. As for loops, I have tried using a for loop, while, and do while. Thanks in advance! // Rock Paper Scissor Shoot Game import java.util.Random; import java.util.Scanner; public class RockPaperSciccor { public static void main(String[] args){ int wins = 0; int losses = 0; int rnd; for(rnd=0;rnd<=10;rnd++) { Random GAME = new Random(); int PC = 1+GAME.nextInt(3); Scanner input = new Scanner (System.in); int SCISSOR, ROCK, PAPER; SCISSOR = 1; ROCK = 2; PAPER = 3; System.out.println(""); System.out.println("Choose Your Weapon! "); System.out.println("1 = Scissor| 2 = Rock| 3 = Paper"); System.out.println(""); int USER

For loop while parsing xml in php?

I am trying to create a for loop that will parse out different elements of xml doc using php. It parses when I put the number of the entry in the line: $s = $xml->entry[0]->children($namespaces['s']); However I tried to replace the number with "i" to count through each of the entries in the xml doc and I get an error (Fatal error: Call to a member function children() on a non-object in /home/content/c/a/s/cashme/html/buylooper/xml.php on line 10). How do I resolve this? <?php $url = 'xml-file.xml'; $xml = simplexml_load_file($url); $namespaces = $xml->entry->getNameSpaces(true); for ($i = 0; $i <= 10; $i += 1){ $s = $xml->entry[i]->children($namespaces['s']); $title = $s->product->title; //print echo $retailer; } ?>