Search Results

Search found 206 results on 9 pages for 'nextint'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Java NoSuchElementException using scanner.nextInt()

    - by othnin
    I am trying to read in a pgm file (512x512 array) and when I read in a larger file I get the error: java.util.NoSuchElementException on reading element (3,97). I have created a much smaller file to read (23x23) and it reads fine. Is there a size limit? I have checked the file and confirmed that there is an int for the value: This appears to be the line it crashes at: fileArray[row][col] = scan.nextInt(); Here is the file: import java.util.Scanner; import java.io.*; public class FileReader { public static void main(String[] args) throws IOException { String fileName = "lena.pgma"; int width, height, maxValue; FileInputStream fileInputStream = null; fileInputStream = new FileInputStream(fileName); Scanner scan = new Scanner(fileInputStream); // Discard the magic number scan.nextLine(); // Discard the comment line scan.nextLine(); // Read pic width, height and max value width = scan.nextInt(); System.out.println("Width: " + width); height = scan.nextInt(); System.out.println("Heigth: " + height); maxValue = scan.nextInt(); fileInputStream.close(); // Now parse the file as binary data FileInputStream fin = new FileInputStream(fileName); DataInputStream dis = new DataInputStream(fin); // look for 4 lines (i.e.: the header) and discard them int numnewlines = 4; while (numnewlines > 0) { char c; do { c = (char)(dis.readUnsignedByte()); } while (c != '\n'); numnewlines--; } // read the image data int[][] fileArray = new int[height][width]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { fileArray[row][col] = scan.nextInt(); System.out.print("(" + row + " ," + col +"): " + fileArray[row][col]+ " "); } System.out.println(); } dis.close(); } } any advise would be appreciated.

    Read the article

  • Java: Infinite loop using Scanner in.hasNextInt()

    - by Tomek
    Hi everyone, I am using the following code: while (invalidInput) { // ask the user to specify a number to update the times by System.out.print("Specify an integer between 0 and 5: "); if (in.hasNextInt()) { // get the update value updateValue = in.nextInt(); // check to see if it was within range if (updateValue >= 0 && updateValue <= 5) { invalidInput = false; } else { System.out.println("You have not entered a number between 0 and 5. Try again."); } } else { System.out.println("You have entered an invalid input. Try again."); } } However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again." Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement: if (in.hasNextInt()) Thanks in advance, Tomek

    Read the article

  • How to convert this procedural programming to object-oriented programming?

    - by manus91
    I have a source code that is needed to be converted by creating classes, objects and methods. So far, I've just done by converting the initial main into a separate class. But I don't know what to do with constructor and which variables are supposed to be private. This is the code : import java.util.*; public class Card{ private static void shuffle(int[][] cards){ List<Integer> randoms = new ArrayList<Integer>(); Random randomizer = new Random(); for(int i = 0; i < 8;) { int r = randomizer.nextInt(8)+1; if(!randoms.contains(r)) { randoms.add(r); i++; } } List<Integer> clonedList = new ArrayList<Integer>(); clonedList.addAll(randoms); Collections.shuffle(clonedList); randoms.addAll(clonedList); Collections.shuffle(randoms); int i=0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ cards[r][c] = randoms.get(i); i++; } } } public static void play() throws InterruptedException { int ans = 1; int preview; int r1,c1,r2,c2; int[][] cards = new int[4][4]; boolean[][] cardstatus = new boolean[4][4]; boolean gameover = false; int moves; Scanner input = new Scanner(System.in); do{ moves = 0; shuffle(cards); System.out.print("Enter the time(0 to 5) in seconds for the preview of the answer : "); preview = input.nextInt(); while((preview<0) || (preview>5)){ System.out.print("Invalid time!! Re-enter time(0 - 5) : "); preview = input.nextInt(); } preview = 1000*preview; System.out.println(" "); for (int i =0; i<4;i++){ for (int j=0;j<4;j++){ System.out.print(cards[i][j]); System.out.print(" "); } System.out.println(""); System.out.println(""); } Thread.sleep(preview); for(int b=0;b<25;b++){ System.out.println(" "); } for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ System.out.print("*"); System.out.print(" "); cardstatus[r][c] = false; } System.out.println(""); System.out.println(" "); } System.out.println(""); do{ do{ System.out.print("Please insert the first card row : "); r1 = input.nextInt(); while((r1<1) || (r1>4)){ System.out.print("Invalid coordinate!! Re-enter first card row : "); r1 = input.nextInt(); } System.out.print("Please insert the first card column : "); c1 = input.nextInt(); while((c1<1) || (c1>4)){ System.out.print("Invalid coordinate!! Re-enter first card column : "); c1 = input.nextInt(); } if(cardstatus[r1-1][c1-1] == true){ System.out.println("The card is already flipped!! Select another card."); System.out.println(""); } }while(cardstatus[r1-1][c1-1] != false); do{ System.out.print("Please insert the second card row : "); r2 = input.nextInt(); while((r2<1) || (r2>4)){ System.out.print("Invalid coordinate!! Re-enter second card row : "); r2 = input.nextInt(); } System.out.print("Please insert the second card column : "); c2 = input.nextInt(); while((c2<1) || (c2>4)){ System.out.print("Invalid coordinate!! Re-enter second card column : "); c2 = input.nextInt(); } if(cardstatus[r2-1][c2-1] == true){ System.out.println("The card is already flipped!! Select another card."); } if((r1==r2)&&(c1==c2)){ System.out.println("You can't select the same card twice!!"); continue; } }while(cardstatus[r2-1][c2-1] != false); r1--; c1--; r2--; c2--; System.out.println(""); System.out.println(""); System.out.println(""); for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ if((r==r1)&&(c==c1)){ System.out.print(cards[r][c]); System.out.print(" "); } else if((r==r2)&&(c==c2)){ System.out.print(cards[r][c]); System.out.print(" "); } else if(cardstatus[r][c] == true){ System.out.print(cards[r][c]); System.out.print(" "); } else{ System.out.print("*"); System.out.print(" "); } } System.out.println(" "); System.out.println(" "); } System.out.println(""); if(cards[r1][c1] == cards[r2][c2]){ System.out.println("Cards Matched!!"); cardstatus[r1][c1] = true; cardstatus[r2][c2] = true; } else{ System.out.println("No cards match!!"); } Thread.sleep(2000); for(int b=0;b<25;b++){ System.out.println(""); } for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ if(cardstatus[r][c] == true){ System.out.print(cards[r][c]); System.out.print(" "); } else{ System.out.print("*"); System.out.print(" "); } } System.out.println(""); System.out.println(" "); } System.out.println(""); System.out.println(""); System.out.println(""); gameover = true; for(int r=0;r<4;r++){ for( int c=0;c<4;c++){ if(cardstatus[r][c]==false){ gameover = false; break; } } if(gameover==false){ break; } } moves++; }while(gameover != true); System.out.println("Congratulations, you won!!"); System.out.println("It required " + moves + " moves to finish it."); System.out.println(""); System.out.print("Would you like to play again? (1=Yes / 0=No) : "); ans = input.nextInt(); }while(ans == 1); } } The main class is: import java.util.*; public class PlayCard{ public static void main(String[] args) throws InterruptedException{ Card game = new Card(); game.play(); } } Should I simplify the Card class by creating other classes? Through this code, my javadoc has no constructtor. So i need help on this!

    Read the article

  • Scanner error that I can't figure out: NoSuchElementException

    - by iaacp
    It's crashing on the third line inside the do-while loop, and doesn't wait for my input: input = kb.nextInt(); Stack trace: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at main.MainDriver.main(MainDriver.java:50) Relevant code: do { displayFullMenu(); System.out.print("Selection: "); input = kb.nextInt(); switch (input) { //Create new survey case 1: currentSurvey = new Survey(); break; //Display current survey case 2: currentSurvey.display(); break; //Save current survey case 3: saveSurvey(currentSurvey); break; //Load a survey case 4: currentSurvey = loadSurvey(); break; //Modify a survey case 5: currentSurvey.modify(); break; /*******************Test Functions*******************/ //Create new test case 6: currentSurvey = new Test(); break; //Display current test case 7: currentSurvey.display(); break; //Save current test case 8: saveSurvey(currentSurvey); break; //Load a test case 9: currentSurvey = loadTest(); break; //Modify a test case 10: currentSurvey.modify(); default: System.out.println("Invalid choice. Please make a valid choice: "); input = kb.nextInt(); System.out.println(); } } while (input != 99); kb.close(); It crashes after I choose option 9. It saves the file correctly, then goes back to the top of the loop, and crashes at the previously mentioned line. I want it to ask for more input. What gives?

    Read the article

  • Java program grading

    - by pasito15
    I've been working on this program for hours and I can't figure out how to get the program to actually print the grades from the scores Text file public class Assign7{ private double finalScore; private double private_quiz1; private double private_quiz2; private double private_midTerm; private double private_final; private final char grade; public Assign7(double finalScore){ private_quiz1 = 1.25; private_quiz2 = 1.25; private_midTerm = 0.25; private_final = 0.50; if (finalScore >= 90) { grade = 'A'; } else if (finalScore >= 80) { grade = 'B'; } else if (finalScore >= 70) { grade = 'C'; } else if (finalScore>= 60) { grade = 'D'; } else { grade = 'F'; } } public String toString(){ return finalScore+":"+private_quiz1+":"+private_quiz2+":"+private_midTerm+":"+private_final; } } this code compiles as well as this one import java.util.*; import java.io.*; public class Assign7Test{ public static void main(String[] args)throws Exception{ int q1,q2; int m = 0; int f = 0; int Record ; String name; Scanner myIn = new Scanner( new File("scores.txt") ); System.out.println( myIn.nextLine() +" avg "+"letter"); while( myIn.hasNext() ){ name = myIn.next(); q1 = myIn.nextInt(); q2 = myIn.nextInt(); m = myIn.nextInt(); f = myIn.nextInt(); Record myR = new Record( name, q1,q2,m,f); System.out.println(myR); } } public static class Record { public Record() { } public Record(String name, int q1, int q2, int m, int f) { } } } once a compile the code i get this which dosent exactly compute the numbers I have in the scores.txt Name quiz1 quiz2 midterm final avg letter Assign7Test$Record@4bcc946b Assign7Test$Record@642423 Exception in thread "main" java.until.InputMismatchException at java.until.Scanner.throwFor(Unknown Source) at java.until.Scanner.next(Unknown Source) at java.until.Scanner.nextInt(Unknown Source) at java.until.Scanner.nextInt(Unknown Source) at Assign7Test.main(Assign7Test.java:25)

    Read the article

  • Problems with instantiating in JAVA

    - by PUPIALEX
    When running, below programme cannot reach the end of the main function.. I am new to JAVA, and cannot find its defections.. I need your help. Thanks. import java.util.*; class Schedule { public String day; private int startTime, endTime; public Schedule(String input_day, int input_start, int input_end) { day = input_day; startTime = input_start; endTime = input_end; } /* clashWith: to check whether this schedule clash with a Schedule called otherSchedule * PRE-Condition : input must be of Schedule type * POST-Condition : return true if two Schedule clash, return false if not. */ public boolean clashWith(Schedule otherSchedule) { if(this.day != otherSchedule.day || this.endTime <= otherSchedule.startTime || this.startTime >= otherSchedule.endTime) return false; return true; } } class Module { String code; Schedule lecture, tutorial, lab; public Module(String input_code, Schedule input_lecture, Schedule input_tutorial, Schedule input_lab) { code = input_code; lecture = input_lecture; tutorial = input_tutorial; lab = input_lab; } /* count: to count number of classes(lecture, tutorial, and lab of only this Module) on day. * For example: when day = "Monday", lecture is on Monday, tutorial is on Monday * but lab is on Tuesday, then return 2. (lecture and tutorial are on Monday). * PRE-Condition : * POST-Condition : */ public int count(String day) { int num = 0; if(lecture.day == day) num++; if(tutorial.day == day) num++; if(lab.day == day) num++; return num; } /* clashWith: to check whether this module clash with a Module called otherModule * PRE-Condition : * POST-Condition : */ public boolean clashWith(Module otherModule) { if(lecture.clashWith(otherModule.lecture) || lecture.clashWith(otherModule.tutorial) || lecture.clashWith(otherModule.lab) ) return true; if(tutorial.clashWith(otherModule.lecture) || tutorial.clashWith(otherModule.tutorial) || tutorial.clashWith(otherModule.lab)) return true; if(lab.clashWith(otherModule.lecture) || lab.clashWith(otherModule.tutorial) || lab.clashWith(otherModule.lab)) return true; return false; } } class Timetable { Vector<Module> listOfModule; public Timetable() { } /* checkClash: to check whether otherModule clash with one of * the modules in our timetable list. * PRE-Condition : * POST-Condition : */ public boolean checkClash(Module otherModule) { for(Module c: listOfModule) if(c.clashWith(otherModule)) return true; return false; } /* add: to add a new module to the timetable list. * PRE-Condition : * POST-Condition : */ public void add(Module module) { listOfModule.add(module); } /* count: to count number of classes on day. * PRE-Condition : * POST-Condition : */ public int count(String day) { int count_day=0; for(Module c: listOfModule) count_day += c.count(day); return count_day; } } public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num_operation; String code ; Timetable userTimetable = new Timetable(); num_operation = input.nextInt(); for(int i=0;i<num_operation;i++) { if(input.next() == "MODULE") { code = input.next(); String day; int start, end; Schedule getLecSche = new Schedule(input.next(),input.nextInt(),input.nextInt()); Schedule getTutSche = new Schedule(input.next(),input.nextInt(),input.nextInt()); Schedule getLabSche = new Schedule(input.next(),input.nextInt(),input.nextInt()); Module userModule = new Module(code, getLecSche, getTutSche, getLabSche); System.out.println("Reached line 162"); if(!userTimetable.checkClash(userModule)) { userTimetable.add(userModule); System.out.println("Added"); } else System.out.println("Clashed"); } else if(input.next() == "COUNT"){ code = input.next(); System.out.println(userTimetable.count(code)); } } } }

    Read the article

  • Java - Draw Cards and Eliminate Cards Problem

    - by Jen
    I am having a problem in this question. I want a system inside a game wherein the player draws 2 cards randomly, and the enemy draws 2 cards randomly. Then, what the program does is to print out to the console the cards the player draw and the enemy's. The cards should not conflict and must not be the same. Then lastly, the program prints out the card that was not drawn by both the player and the enemy. Here's how I did it but it was lengthy and full of errors: import java.util.Random; public class Draw { public static Random random = new Random(); public static String cards[] = {"Hall", "Kitchen", "Billiard", "Study", "Pool"}; public static int playercounter; public static int enemycounter; public static String playercardA = null; public static String playercardB = null; public static String enemycardA = null; public static String enemycardB = null; public String lastcard = null; public static void playercardAdraw() { playercounter = random.nextInt(5); playercardA = cards[playercounter]; } public static void playercardBdraw() { playercounter=random.nextInt(5); playercardB= cards[playercounter]; if (playercardB==playercardA || playercardB == enemycardA || playercardB == enemycardB) { return; } } public static void enemycardAdraw () { enemycounter = random.nextInt(5); enemycardA=cards[enemycounter]; if (enemycardA == playercardA || enemycardA == playercardB) { return; } } public static void enemycardBdraw () { enemycounter = random.nextInt(5); enemycardB=cards[enemycounter]; if (enemycardB == playercardA || enemycardB == playercardB || enemycardB == enemycardA) { return; } } public static void main (String args []) { System.out.println("Starting to draw..."); System.out.println("Player's Turn: "); playercardAdraw(); System.out.println("Player's first card: " + playercardA); playercardBdraw(); System.out.println("Player's second card: " + playercardB); System.out.println("Enemy's Turn: "); enemycardAdraw(); System.out.println("Enemy's first card: " + enemycardA); enemycardBdraw(); System.out.println("Enemy's Second card: " + enemycardB); } }

    Read the article

  • Draw Cards and Eliminate Cards Problem

    - by Jen
    I am having a problem in this question. I want a system inside a game wherein the player draws 2 cards randomly, and the enemy draws 2 cards randomly. Then, what the program does is to print out to the console the cards the player draw and the enemy's. The cards should not conflict and must not be the same. Then lastly, the program prints out the card that was not drawn by both the player and the enemy. Here's how I did it but it was lengthy and full of errors: import java.util.Random; public class Draw { public static Random random = new Random(); public static String cards[] = {"Hall", "Kitchen", "Billiard", "Study", "Pool"}; public static int playercounter; public static int enemycounter; public static String playercardA = null; public static String playercardB = null; public static String enemycardA = null; public static String enemycardB = null; public String lastcard = null; public static void playercardAdraw() { playercounter = random.nextInt(5); playercardA = cards[playercounter]; } public static void playercardBdraw() { playercounter=random.nextInt(5); playercardB= cards[playercounter]; if (playercardB==playercardA || playercardB == enemycardA || playercardB == enemycardB) { return; } } public static void enemycardAdraw () { enemycounter = random.nextInt(5); enemycardA=cards[enemycounter]; if (enemycardA == playercardA || enemycardA == playercardB) { return; } } public static void enemycardBdraw () { enemycounter = random.nextInt(5); enemycardB=cards[enemycounter]; if (enemycardB == playercardA || enemycardB == playercardB || enemycardB == enemycardA) { return; } } public static void main (String args []) { System.out.println("Starting to draw..."); System.out.println("Player's Turn: "); playercardAdraw(); System.out.println("Player's first card: " + playercardA); playercardBdraw(); System.out.println("Player's second card: " + playercardB); System.out.println("Enemy's Turn: "); enemycardAdraw(); System.out.println("Enemy's first card: " + enemycardA); enemycardBdraw(); System.out.println("Enemy's Second card: " + enemycardB); } }

    Read the article

  • Programming an Android Button to update EditText views

    - by bergler77
    Ok guys, I have a button in android that i'm trying to use to update 8 EditText Views with different random numbers. Everything works up until I click the button. It appears I am missing a resource according to the debugger, but I'm not sure what. I've tried several different ways of implementing the button. Here is what I have after looking at several posts. import java.util.Random; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MyCharNewChar extends MyCharActivity { private OnClickListener randomButtonListener = new OnClickListener(){ public void onClick(View v) { //Button creates a set of random numbers and updates the values //of the EditText views. Random rand = new Random(); int STR = 1 + rand.nextInt(12); int AGI = 1 + rand.nextInt(12); int DEX = 1 + rand.nextInt(12); int WIS = 1 + rand.nextInt(12); int INT = 1 + rand.nextInt(12); int CON = 1 + rand.nextInt(12); int HP = 1 + rand.nextInt(20); int AC = 1 + rand.nextInt(6); EditText str = (EditText) findViewById(R.id.str); str.setText(STR); EditText agi = (EditText) findViewById(R.id.agi); agi.setText(AGI); EditText dex = (EditText) findViewById(R.id.dex); dex.setText(DEX); EditText wis = (EditText) findViewById(R.id.wis); wis.setText(WIS); EditText intel = (EditText) findViewById(R.id.intel); intel.setText(INT); EditText con = (EditText) findViewById(R.id.con); con.setText(CON); EditText hp = (EditText) findViewById(R.id.baseHP); hp.setText(HP); EditText ac = (EditText) findViewById(R.id.baseAC); ac.setText(AC); } }; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.newchar); Button randomButton = (Button) findViewById(R.id.randomButton); randomButton.setOnClickListener(randomButtonListener); } } Here is the xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearlayoutNew1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/background" > <TextView android:id="@+id/newCharLabel" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/new_character_screen" android:textSize="24dp" android:textColor="@color/splash" android:textStyle="bold" android:gravity="center"/> <TextView android:id="@+id/nameLabel" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/nameLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" > <requestFocus /> </EditText> <TableLayout android:id="@+id/statsLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <TableRow android:id="@+id/tableRow01" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <TextView android:id="@+id/strLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/strLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/str" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number" /> <TextView android:id="@+id/agiLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/agiLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/agi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> <TextView android:id="@+id/dexLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dexLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/dex" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> </TableRow> <TableRow android:id="@+id/tableRow02" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <TextView android:id="@+id/intLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/intLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/intel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> <TextView android:id="@+id/wisLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/wisLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/wis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> <TextView android:id="@+id/conLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/conLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/con" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> </TableRow> </TableLayout> <LinearLayout android:id="@+id/linearlayoutNew02" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:gravity="center"> <TextView android:id="@+id/baseHPLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hpLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/baseHP" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> <TextView android:id="@+id/baseACLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/acLabel" android:textSize="18dp" android:textColor="@color/splash"/> <EditText android:id="@+id/baseAC" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="3" android:inputType="number"/> </LinearLayout> <LinearLayout android:id="@+id/linearlayoutNew03" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/randomButton" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/randomButton" android:textSize="16dp" android:clickable="true"/> </LinearLayout> </LinearLayout> I have also tried setting the onClick in xml to setup a specific onClick method. Still the same error so I must have a problem elsewhere. Any suggestions would be great!

    Read the article

  • Stack Overflow Error

    - by dylanisawesome1
    I recently created a recursive cave algorithm, and would like to have more extensive caves, but get a stack overflow after re-cursing a couple times. Any advice? Here's my code: for(int i=0;i<100;i++) { int rand = new Random().nextInt(100); if(rand<=20) { if(curtile.bounds.y-40>500+new Random().nextInt(20)) digDirection(Direction.UP); } if(rand<=40 && rand>20) { if(curtile.bounds.y+40<m.height) digDirection(Direction.DOWN); } if(rand<=60 && rand>40) { if(curtile.bounds.x-40>0) digDirection(Direction.LEFT); } if(rand<=80 && rand>60) { if(curtile.bounds.x+40<m.width) digDirection(Direction.RIGHT); } } } public void digDirection(Direction d) { if(new Random().nextInt(100)<=10) { new Miner(curtile, map); // try { // Thread.sleep(2); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //Tried this to avoid stack overflow. Didn't work. }

    Read the article

  • Better way to generate enemies of different sub-classes

    - by KDiTraglia
    So lets pretend I have an enemy class that has some generic implementation and inheriting from it I have all the specific enemies of my game. There are points in my code that I need to check whether an enemy is a specific type, but in Java I have found no easier way than this monstrosity... //Must be a better way to do this if ( enemy.class.isAssignableFrom(Ninja.class) ) { ... } My partner on the project saw these and changed them to use an enum system instead public class Ninja extends Enemy { //EnemyType is an enum containing all our enemy types public EnemyType = EnemyTypes.NINJA; } if (enemy.EnemyType = EnemyTypes.NINJA) { ... } I also have found no way to generate enemies on varying probabilities besides this for (EnemyTypes types : enemyTypes) { if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) { enemy = createEnemy(types.getEnemyType()); break; } } private static Enemy createEnemy(EnemyType type) { switch (type) { case NINJA: return new Ninja(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); case GORILLA: return new Gorilla(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); case TREX: return new TRex(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); //etc } return null } I know java is a little weak at dynamic object creation, but is there a better way to implement this in a way such like this for (EnemyTypes types : enemyTypes) { if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) { //Change enemyTypes to hold the classes of the enemies I can spawn enemy = types.getEnemyType().class.newInstance() break; } } Is the above possible? How would I declare enemyTypes to hold the classes if so? Everything I have tried so far as generated compile errors and general frustration, but I figured I might ask here before I completely give up to the huge mass that is the createEveryEnemy() method. All the enemies do inherit from the Enemy class (which is what the enemy variable is declared as). Also is there a better way to check which type a particular enemy that is shorter than enemy.class.isAssignableFrom(Ninja.class)? I'd like to ditch the enums entirely if possible, since they seem repetitive when the class name itself holds that information.

    Read the article

  • Add & Show data in Java ArrayList [closed]

    - by Kaidul Islam Sazal
    I have a class inside a main class : static class Graph{ static int u, v, cost; } I have instantiated an arraylist of the class: static List<Graph> g = new ArrayList<Graph>(); And I insert several values into the arraylist like this: Scanner input = new Scanner(System.in); for (int i = 0; i < edge_no; i++) { Graph e = new Graph(); e.u = input.nextInt(); e.v = input.nextInt(); e.cost = input.nextInt(); g.add(e); } And I print it like this: for (int i = 0; i < edge_no; i++) { System.out.println(g.get(i).u + " " + g.get(i).v + " " + g.get(i).cost); } But the problem is that, when I print it, only the last value is shown all the time.It seems that, all the previous values are over-written with it. Input : 1 2 5 1 3 8 2 3 9 Output: 2 3 9 2 3 9 2 3 9 Expected output is just like the input.But I can't fix the problem as I am novice in java.

    Read the article

  • Random generates same number in java

    - by user1613360
    This is my java code. import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; class search { private int numelem; private int[] input=new int[100]; public void setNumofelem() { System.out.println("Enter the total numebr of elements"); Scanner yz=new Scanner(System.in); numelem=yz.nextInt(); } public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { input[j]=rand.nextInt(max)+1; } } public void printinput() { int b=numelem,t=0; while(true) if(b!=0) { System.out.print(" "+input[t]); b--; t++; } else break; } } public class mycode { public static void main(String args[]) throws Exception { search a=new search(); a.setNumofelem(); a.randomnumber(); a.printinput(); } } Now the function randomnumber() just returns the same number.The function executes perfectly if I execute it as a separate java program but fails miserably if I call it using an object.I have also tried the following variations but nothing works everything return the same number. Variation 1: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); input[j]=rand.nextInt(max)+1; } } Variation 2: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Variation 3: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Sample input/Output: Enter the number of elements: 5 23 23 23 23 23 23

    Read the article

  • How to store multiple variables from a File Input of unknown size in Java?

    - by AlphaOmegaStrife
    I'm a total beginner with my first programming assignment in Java. For our programming assignment, we will be given a .txt file of students like so: 3 345 Lisa Miller 890238 Y 2 <-(Number of classes) Mathematics MTH345 4 A Physics PHY357 3 B Bill Wilton 798324 N 2 English ENG378 3 B Philosophy PHL534 3 A Dandy Goat 746333 Y 1 History HIS101 3 A" The teacher will give us a .txt file on the day of turning it in with a list of unknown students. My problem is: I have a specific class for turning the data from the file into variables to be used for a different class in printing it to the screen. However, I do not know of a good way to get the variables from the input file for the course numbers, since that number is not predetermined. The only way I can think of to iterate over that unknown amount is using a loop, but that would just overwrite my variables every time. Also, the teacher has requested that we not use any JCL classes (I don't really know what this means.) Sorry if I have done a poor job of explaining this, but I can't think of a better way to conceptualize it. Let me know if I can clarify. Edit: public static void analyzeData() { Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt")); } catch (FileNotFoundException e) { System.out.println("File Programming Assignment 1 Data.txt could not be found or opened."); System.exit(0); } int numberOfStudents = inputStream.nextInt(); int tuitionPerHour = inputStream.nextInt(); String firstName = inputStream.next(); String lastname = inputStream.next(); String isTuitionPaid = inputStream.next(); int numberOfCourses = inputStream.nextInt(); String courseName = inputStream.next(); String courseNumber = inputStream.next(); int creditHours = inputStream.nextInt(); String grade = inputStream.next(); To show the methods I am using now, I am just using a Scanner to read from the file and for Scanner inputStream, I am using nextInt() or next() to get variables from the file. Obviously this will not work when I do not know exactly how many classes each student will have.

    Read the article

  • Collision between sprites in game programming?

    - by Lyn Maxino
    I've since just started coding for an android game using eclipse. I've read Beginning Android Game Programming and various other e-books. Recently, I've encountered a problem with collision between sprites. I've used this code template for my program. package com.project.CAI_test; import java.util.Random; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; public class Sprite { // direction = 0 up, 1 left, 2 down, 3 right, // animation = 3 back, 1 left, 0 front, 2 right int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 }; private static final int BMP_ROWS = 4; private static final int BMP_COLUMNS = 3; private static final int MAX_SPEED = 5; private GameView gameView; private Bitmap bmp; private int x = 0; private int y = 0; private int xSpeed; private int ySpeed; private int currentFrame = 0; private int width; private int height; public Sprite(GameView gameView, Bitmap bmp) { this.width = bmp.getWidth() / BMP_COLUMNS; this.height = bmp.getHeight() / BMP_ROWS; this.gameView = gameView; this.bmp = bmp; Random rnd = new Random(); x = rnd.nextInt(gameView.getWidth() - width); y = rnd.nextInt(gameView.getHeight() - height); xSpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED; ySpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED; } private void update() { if (x >= gameView.getWidth() - width - xSpeed || x + xSpeed <= 0) { xSpeed = -xSpeed; } x = x + xSpeed; if (y >= gameView.getHeight() - height - ySpeed || y + ySpeed <= 0) { ySpeed = -ySpeed; } y = y + ySpeed; currentFrame = ++currentFrame % BMP_COLUMNS; } public void onDraw(Canvas canvas) { update(); int srcX = currentFrame * width; int srcY = getAnimationRow() * height; Rect src = new Rect(srcX, srcY, srcX + width, srcY + height); Rect dst = new Rect(x, y, x + width, y + height); canvas.drawBitmap(bmp, src, dst, null); } private int getAnimationRow() { double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2); int direction = (int) Math.round(dirDouble) % BMP_ROWS; return DIRECTION_TO_ANIMATION_MAP[direction]; } public boolean isCollition(float x2, float y2) { return x2 > x && x2 < x + width && y2 > y && y2 < y + height; } } The above code only detects collision between the generated sprites and the surface border. What I want to achieve is a collision detection that is controlled by the update function without having to change much of the coding. Probably several lines placed in the update() function. Tnx for any comment/suggestion.

    Read the article

  • Java Performance measurement

    - by portoalet
    Hi, I am doing some Java performance comparison between my classes, and wondering if there is some sort of Java Performance Framework to make writing performance measurement code easier? I.e, what I am doing now is trying to measure what effect does it have having a method as "synchronized" as in PseudoRandomUsingSynch.nextInt() compared to using an AtomicInteger as my "synchronizer". So I am trying to measure how long it takes to generate random integers using 3 threads accessing a synchronized method looping for say 10000 times. I am sure there is a much better way doing this. Can you please enlighten me? :) public static void main( String [] args ) throws InterruptedException, ExecutionException { PseudoRandomUsingSynch rand1 = new PseudoRandomUsingSynch((int)System.currentTimeMillis()); int n = 3; ExecutorService execService = Executors.newFixedThreadPool(n); long timeBefore = System.currentTimeMillis(); for(int idx=0; idx<100000; ++idx) { Future<Integer> future = execService.submit(rand1); Future<Integer> future1 = execService.submit(rand1); Future<Integer> future2 = execService.submit(rand1); int random1 = future.get(); int random2 = future1.get(); int random3 = future2.get(); } long timeAfter = System.currentTimeMillis(); long elapsed = timeAfter - timeBefore; out.println("elapsed:" + elapsed); } the class public class PseudoRandomUsingSynch implements Callable<Integer> { private int seed; public PseudoRandomUsingSynch(int s) { seed = s; } public synchronized int nextInt(int n) { byte [] s = DonsUtil.intToByteArray(seed); SecureRandom secureRandom = new SecureRandom(s); return ( secureRandom.nextInt() % n ); } @Override public Integer call() throws Exception { return nextInt((int)System.currentTimeMillis()); } } Regards

    Read the article

  • what is the problem in ATM machine program

    - by Have alook
    in this prigramm when the account number is uncorrect it should display a message to write a gain but when i wrote a gain by corrrect account number always it diplay the result of first account also there is aproblem in PIN number ,the use have only three time to try if he enter wrong numbe and if enter three times wrong it should stop the program but it complete to the last part I dont know why pleas help me this is my proram import java.util.*; class assignment2_70307{ public static void main(String args[]){ Scanner m=new Scanner(System.in); int i; i=0; int [] accountNo =new int[7] ;//declear the Accont number array accountNo [0] =1111; accountNo [1] =2222; accountNo [2] =3333; accountNo [3] =4444; accountNo [4] =5555; accountNo [5] =6666; accountNo [6] =7777; int [] PINno =new int[7]; //declear the PIN number array PINno [0] =1234; PINno [1] =5678; PINno [2] =9874; PINno [3] =6523; PINno [4] =1236; PINno [5] =4569; PINno [6] =8521; String [] CusomerNm =new String[7]; //dclear the customer name CusomerNm [0] ="Ali"; CusomerNm [1] ="Ahmed"; CusomerNm [2] ="Amal"; CusomerNm [3] ="Said"; CusomerNm [4] ="Rashid"; CusomerNm [5] ="Fatema"; CusomerNm [6] ="Mariam"; double [] Balance =new double[7]; //declear the Balane array Balance [0] =100.50; Balance [1] =5123.00; Balance [2] =12.00; Balance [3] =4569.00; Balance [4] =1020.25; Balance [5] =0.00; Balance [6] =44.10; System.out.println("Wellcome to mini ATM Machine"); int accountno,pino; accountno=0; pino=0; System.out.println("Please Enter your account number: or -1 to stop" ); accountno=m.nextInt(); if (accountno==accountNo[0]) System.out.print("Customer Name: "+CusomerNm [0]+ "\n" ); else if (accountno==accountNo[1]) System.out.print("Customer Name: "+CusomerNm [1]+ "\n" ); else if (accountno==accountNo[2]) System.out.print("Customer Name: "+CusomerNm [2]+ "\n" ); else if (accountno==accountNo[3]) System.out.print("Customer Name: "+CusomerNm [3]+ "\n" ); else if (accountno==accountNo[4]) System.out.print("Customer Name: "+CusomerNm [4]+ "\n" ); else if (accountno==accountNo[5]) System.out.print("Customer Name: "+CusomerNm [5]+ "\n" ); else if (accountno==accountNo[6]) System.out.print("Customer Name: "+CusomerNm [6]+ "\n" ); // else if (accountNo[0]==-1) //break; else { System.out.println("The account dose not exist,please try again"); //accountNo[i]=m.nextInt(); accountno=m.nextInt(); if(accountNo[i]==accountno) System.out.println("Customer Name: "+CusomerNm[i] ); else System.out.println("The account dose not exist,please try again"); accountno=m.nextInt(); System.out.println("Customer Name: "+CusomerNm[i] ); } System.out.print("Enter your PIN number:"); PINno[i]=m.nextInt(); if(PINno[i]==1234) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [0]+ "Rial"); //return 0; } else if(PINno[i]==5678) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [1]+ "Rial"); // return 1; } else if(PINno[i]==9874) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [2]+ "Rial"); // return 2; } else if(PINno[i]==6523) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [3]+ "Rial"); // return 3; } else if(PINno[i]==1236) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [4]+ "Rial"); // return 4; } else if(PINno[i]==4569) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [5]+ "Rial"); // return 5; } else if(PINno[i]==8521) { System.out.println(PINno[i]); System.out.println("Balance:"+Balance [6]+ "Rial"); // return 6; } else {System.out.println("try again"); //return 7; //if its wrong u can enter PIN number three times only for( i=0;i<2;i++) { System.out.println("enter pin again"); PINno[i]=m.nextInt(); String ss; //ss = "MAnal"; // goto ss ; } } //ss = "m"; int x; x=0; System.out.println("Enter the option from the list /n 1.Deposit /n 2.Withdraw /n 3.Balance"); x=m.nextInt(); double balance,amount; balance=0; amount=0; double deposit ,Withdraw; deposit=0; Withdraw=0; if (x==1){ System.out.println("Enter the amont you want to deposit:"+amount); amount=m.nextDouble(); Balance [i]=Balance [i]+amount; System.out.println("your balance ="+Balance [i]); } else if (x==2) { System.out.println("Enter the amont to withdraw:"); amount=m.nextDouble(); System.out.print(amount); if(Withdraw<=Balance [i]) { Balance [i]=Balance [i]-amount; System.out.println("your balance ="+Balance [i]); } else { System.out.println("sorry,please enter the amont less or equal your balance"); System.out.println(Balance [i]); } } else { if(x==1) { Balance [i]=Balance [i]+deposit; System.out.println("your current balance is :" +Balance [i]); } else { Balance [i]=Balance [i]-Withdraw; System.out.println("your current balance is :"+Balance [i]); } System.out.println("Thank you"); // err() } } }

    Read the article

  • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)

    - by David
    Here's some sample code: import java.util.Scanner; class In { public static void main (String[]arg) { Scanner in = new Scanner (System.in) ; System.out.println ("how many are invading?") ; int a = in.nextInt() ; System.out.println (a) ; } } if i run the program and give it an int like 4then everything goes fine. if, on the other hand, i answer too many it doesn't laugh at my funny joke. instead i get this: (as expected) Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at In.main(In.java:9) is there a way so that i can make it so that it either ignores entries that aren't ints or re prompts with "how many are invading?"? i'd like to know how to do both of these.

    Read the article

  • Whats wrong with my Random?

    - by David
    Here's my import statement: import java.util.*; Here it is in main: Random Rand = new Random() ; Here it is in a public void method : int a - 0 ; while (!done) { int a = Rand.nextInt(10) ; if (debug) stuff ; if (possibles[a]==1) done = true ; } Here's the error message i get: TicTacToe.java:85: cannot find symbol symbol : method nextInt(int) location: class Rand a = Rand.nextInt(10) ; ^ Whats going wrong here? it seems like i've done everything right to me.

    Read the article

  • Collision Error

    - by Manji
    I am having trouble with collision detection part of the game. I am using touch events to fire the gun as you will see in the video. Note, the android icon is a temporary graphic for the bullets When ever the user touches (represented by clicks in the video)the bullet appears and kills random sprites. As you can see it never touches the sprites it kills or kill the sprites it does touch. My Question is How do I fix it, so that the sprite dies when the bullet hits it? Collision Code snippet: //Handles Collision private void CheckCollisions(){ synchronized(mSurfaceHolder){ for (int i = sprites.size() - 1; i >= 0; i--){ Sprite sprite = sprites.get(i); if(sprite.isCollision(bullet)){ sprites.remove(sprite); mScore++; if(sprites.size() == 0){ mLevel = mLevel +1; currentLevel++; initLevel(); } break; } } } } Sprite Class Code Snippet: //bounding box left<right and top>bottom int left ; int right ; int top ; int bottom ; public boolean isCollision(Beam other) { // TODO Auto-generated method stub if(this.left>other.right || other.left<other.right)return false; if(this.bottom>other.top || other.bottom<other.top)return false; return true; } EDIT 1: Sprite Class: public class Sprite { // direction = 0 up, 1 left, 2 down, 3 right, // animation = 3 back, 1 left, 0 front, 2 right int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 }; private static final int BMP_ROWS = 4; private static final int BMP_COLUMNS = 3; private static final int MAX_SPEED = 5; private HitmanView gameView; private Bitmap bmp; private int x; private int y; private int xSpeed; private int ySpeed; private int currentFrame = 0; private int width; private int height; //bounding box left<right and top>bottom int left ; int right ; int top ; int bottom ; public Sprite(HitmanView gameView, Bitmap bmp) { this.width = bmp.getWidth() / BMP_COLUMNS; this.height = bmp.getHeight() / BMP_ROWS; this.gameView = gameView; this.bmp = bmp; Random rnd = new Random(); x = rnd.nextInt(gameView.getWidth() - width); y = rnd.nextInt(gameView.getHeight() - height); xSpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED; ySpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED; } private void update() { if (x >= gameView.getWidth() - width - xSpeed || x + xSpeed <= 0) { xSpeed = -xSpeed; } x = x + xSpeed; if (y >= gameView.getHeight() - height - ySpeed || y + ySpeed <= 0) { ySpeed = -ySpeed; } y = y + ySpeed; currentFrame = ++currentFrame % BMP_COLUMNS; } public void onDraw(Canvas canvas) { update(); int srcX = currentFrame * width; int srcY = getAnimationRow() * height; Rect src = new Rect(srcX, srcY, srcX + width, srcY + height); Rect dst = new Rect(x, y, x + width, y + height); canvas.drawBitmap(bmp, src, dst, null); } private int getAnimationRow() { double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2); int direction = (int) Math.round(dirDouble) % BMP_ROWS; return DIRECTION_TO_ANIMATION_MAP[direction]; } public boolean isCollision(float x2, float y2){ return x2 > x && x2 < x + width && y2 > y && y2 < y + height; } public boolean isCollision(Beam other) { // TODO Auto-generated method stub if(this.left>other.right || other.left<other.right)return false; if(this.bottom>other.top || other.bottom<other.top)return false; return true; } } Bullet Class: public class Bullet { int mX; int mY; private Bitmap mBitmap; //bounding box left<right and top>bottom int left ; int right ; int top ; int bottom ; public Bullet (Bitmap mBitmap){ this.mBitmap = mBitmap; } public void draw(Canvas canvas, int mX, int mY) { this.mX = mX; this.mY = mY; canvas.drawBitmap(mBitmap, mX, mY, null); } }

    Read the article

  • How to create reproducible probability in map generation?

    - by nickbadal
    So for my game, I'm using perlin noise to generate regions of my map (water/land, forest/grass) but I'd also like to create some probability based generation too. For instance: if(nextInt(10) > 2 && tile.adjacentTo(Type.WATER)) tile.setType(Type.SAND); This works fine, and is even reproduceable (based on a common seed) if the nextInt() calls are always in the same order. The issue is that in my game, the world is generated on demand, based on the player's location. This means, that if I explore the map differently, and the chunks of the map are generated in a different order, the randomness is no longer consistent. How can I get this sort of randomness to be consistent, independent of call order? Thanks in advance :)

    Read the article

  • New to Java Programming - Error help

    - by JJJ
    I am going through a Java book and drafting the examples and have run into the following error when compiling this code. Any help would be appreciated thank you. Error: Main.java:3: class Addition is public, should be declared in a file named Addition.java public class Addition        ^ 1 error Code: import java.io.*; import java.util.Scanner; public class Addition {   public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in);  int number1; int number2; int sum; System.out.print( "Enter first digit: " ); number1 = input.nextInt(); System.out.print( "Enter second digit:" ); number2 = input.nextInt(); sum = number1 + number2; System.out.printf( "Sum is %d\n, sum" );      } }

    Read the article

  • How to save file and read

    - by Jessy
    Hello everyone, I create a program that place random image in grid layout format. The size of the grid layout is 6 x 6 = 36. Only 10 were filled with images (each image was different) and the rest were empty. freeimagehosting.net/uploads/bfb7e85f63.jpg How can I save it to a file and read it again, so it will display the same images with same placement on the grid? Here is the code that I used to save the images: //image file String []arrPic = {"pic1.jpg","pic2.jpg","pic3.jpg","pic4.jpg","pic5.jpg","pic6.jpg","pic7.jpg","pic8.jpg","pic9.jpg","pic10.jpg",,"pic11.jpg","pic12.jpg","pic13.jpg"}; ArrayList<String> pictures = new ArrayList<String>(Arrays.asList(arrPic)); ArrayList<String> file = new ArrayList<String>(); JPanel pDraw = new JPanel(new GridLayout(6,6,2,2)); ... //fill all grids with empty label for (int i =0; i<(6*6); i++){ JLabel lbl = new JLabel(""); pDraw.add(lbl); } ... //Choose random box to be filled with images for(int i=0; i<10; i++){ Boolean number = true; while(number){ int n = rand.nextInt(35); if(!(arraylist.contains(n))) number = false; arraylist.add(n); } //fill the grids with images for(int i=0; i<arraylist.size(); i++){ //select random image from arraylist int index = rand.nextInt (pictures.size()); String fileName = (String) pictures.get(index ); //find the image file icon = createImageIcon(fileName); //save the file in a new file file.add(fileName); //rescaled the image int x = rand.nextInt(50)+50; int y = rand.nextInt(50)+50; Image image = icon.getImage().getScaledInstance(x,y,Image.SCALE_SMOOTH); icon.setImage(image); //remove empty label and replace it with an image int one = (Integer) arraylist.get(i); pDraw.remove(one); final JLabel label; pDraw.add(label,one); }

    Read the article

  • Question about InputMismatchException while using Scanner

    - by aser
    The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: $%.2f %n",BeginningBalance); outFile.printf("Ending Balance: $%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: $%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: $%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: $%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >