Help with simple program please!

Hi. I am brand new to Java and pretty new to programming in general. I am writing a project for a class where we have to output the index at which a certain "target" string matches the "source" string. I'm stuck. I thought my code would make "compare" a string of length target.length()? Any help is greatly appreciated. Thanks!
public static ArrayList<Integer> matches(String source, String target) {
// check preconditions
assert (source != null) && (source.length() > 0)
     && (target != null) && (target.length() > 0): "matches: violation of precondition";
ArrayList<Integer> result = new ArrayList<Integer>();
String compare = "";
for (int i=0; i<source.length()-target.length()+1;i++){
     int count = 0;
     for (int k=i; k<i+target.length(); k++){
          compare = compare + source.charAt(k);
     for (int j=0; j<target.length(); j++){
          if (target.charAt(j) == compare.charAt(j)){
               count ++;
     if (count == target.length()){
          result.add(i);
          return result;
}

I apologize, I am new to the forums and posted that code horribly. Here is the accurate code.
    public static ArrayList<Integer> matches(String source, String target) {
        // check preconditions
        assert (source != null) && (source.length() > 0)
             && (target != null) && (target.length() > 0): "matches: violation of precondition";
        ArrayList<Integer> result = new ArrayList<Integer>();
        String compare = "";
        for (int i=0; i<source.length()-target.length()+1;i++){
             int count = 0;
             for (int k=i; k<i+target.length(); k++){
                  compare = compare + source.charAt(k);
             for (int j=0; j<target.length(); j++){
                  if (target.charAt(j) == compare.charAt(j)){
                       count ++;
             if (count == target.length()){
                  result.add(i);
          return result;
    }

Similar Messages

  • Need some help with a program Please.

    Well, im new here, im new to java, so i need your help, i have to make a connect four program, my brother "Kind of" helped me and did a program for me, but the problem is i cant use some of those commands in the program and i have to replace them with what ive learned, so i will post the program and i will need your help to modify it for me.
    and for these programs, also i want help for:
    They have errors and i cant fix'em
    the commands that i've leaned:
    If statements, for loops, while loops,do while, strings, math classes, swithc statement, else if,logical operators,methods, one and two dimensional arrays.
    Thanx in advance,
    truegunner
    // Fhourstones 3.0 Board Logic
    // Copyright 2000-2004 John Tromp
    import java.io.*;
    class Connect4 {
    static long color[]; // black and white bitboard
    static final int WIDTH = 7;
    static final int HEIGHT = 6;
    // bitmask corresponds to board as follows in 7x6 case:
    // . . . . . . . TOP
    // 5 12 19 26 33 40 47
    // 4 11 18 25 32 39 46
    // 3 10 17 24 31 38 45
    // 2 9 16 23 30 37 44
    // 1 8 15 22 29 36 43
    // 0 7 14 21 28 35 42 BOTTOM
    static final int H1 = HEIGHT+1;
    static final int H2 = HEIGHT+2;
    static final int SIZE = HEIGHT*WIDTH;
    static final int SIZE1 = H1*WIDTH;
    static final long ALL1 = (1L<<SIZE1)-1L; // assumes SIZE1 < 63
    static final int COL1 = (1<<H1)-1;
    static final long BOTTOM = ALL1 / COL1; // has bits i*H1 set
    static final long TOP = BOTTOM << HEIGHT;
    int moves[],nplies;
    byte height[]; // holds bit index of lowest free square
    public Connect4()
    color = new long[2];
    height = new byte[WIDTH];
    moves = new int[SIZE];
    reset();
    void reset()
    nplies = 0;
    color[0] = color[1] = 0L;
    for (int i=0; i<WIDTH; i++)
    height[i] = (byte)(H1*i);
    public long positioncode()
    return 2*color[0] + color[1] + BOTTOM;
    // color[0] + color[1] + BOTTOM forms bitmap of heights
    // so that positioncode() is a complete board encoding
    public String toString()
    StringBuffer buf = new StringBuffer();
    for (int i=0; i<nplies; i++)
    buf.append(1+moves);
    buf.append("\n");
    for (int w=0; w<WIDTH; w++)
    buf.append(" "+(w+1));
    buf.append("\n");
    for (int h=HEIGHT-1; h>=0; h--) {
    for (int w=h; w<SIZE1; w+=H1) {
    long mask = 1L<<w;
    buf.append((color[0]&mask)!= 0 ? " @" :
    (color[1]&mask)!= 0 ? " 0" : " .");
    buf.append("\n");
    if (haswon(color[0]))
    buf.append("@ won\n");
    if (haswon(color[1]))
    buf.append("O won\n");
    return buf.toString();
    // return whether columns col has room
    final boolean isplayable(int col)
    return islegal(color[nplies&1] | (1L << height[col]));
    // return whether newboard lacks overflowing column
    final boolean islegal(long newboard)
    return (newboard & TOP) == 0;
    // return whether newboard is legal and includes a win
    final boolean islegalhaswon(long newboard)
    return islegal(newboard) && haswon(newboard);
    // return whether newboard includes a win
    final boolean haswon(long newboard)
    long y = newboard & (newboard>>HEIGHT);
    if ((y & (y >> 2*HEIGHT)) != 0) // check diagonal \
    return true;
    y = newboard & (newboard>>H1);
    if ((y & (y >> 2*H1)) != 0) // check horizontal -
    return true;
    y = newboard & (newboard>>H2); // check diagonal /
    if ((y & (y >> 2*H2)) != 0)
    return true;
    y = newboard & (newboard>>1); // check vertical |
    return (y & (y >> 2)) != 0;
    void backmove()
    int n;
    n = moves[--nplies];
    color[nplies&1] ^= 1L<<--height[n];
    void makemove(int n)
    color[nplies&1] ^= 1L<<height[n]++;
    moves[nplies++] = n;
    public static void main(String argv[])
    Connect4 c4;
    String line;
    int col=0, i, result;
    long nodes, msecs;
    c4 = new Connect4();
    c4.reset();
    BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
    for (;;) {
    System.out.println("position " + c4.positioncode() + " after moves " + c4 + "enter move(s):");
    try {
    line = dis.readLine();
    } catch (IOException e) {
    System.out.println(e);
    System.exit(0);
    return;
    if (line == null)
    break;
    for (i=0; i < line.length(); i++) {
    col = line.charAt(i) - '1';
    if (col >= 0 && col < WIDTH && c4.isplayable(col))
    c4.makemove(col);
    By the way im using Ready to program for the programming.

    You can't really believe that his brother did this
    for him...I did miss that copyright line at the beginning when
    I first looked it over, but you know, if it had been
    his brother, I'd be kinda impressed. This wasn't a
    25 line program. It actually would have required
    SOME thought. I doubt my brother woulda done that
    for me (notwithstanding the fact that I wouldn't need
    help for that program, and my brother isn't a
    programmer).I originally missed the comments at the top but when I saw the complexity of what was written then I knew that it was too advanced for a beginner and I relooked through the code and saw the comments.

  • Help with simple programming

    Hello everyone.
    First time posting, i hope someone would be able to help me out. There are 5 classes that i have to do, but i only need help with one of them. I've been stuck on this one pretty long and can't continue without it.
    Instructions:
    •     Has boolean data member face, either HEADS or TAILS.
    •     Has a Random data member flipper which is instantiated in the constructor.
    •     Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    •     Method getFace() returns the face showing on the coin.
    •     void method flip() randomly selects HEADS or TAILS.
    package coinflip;
    import java.util.Random;
    * @author Blank
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            return flip_coin;
          Coin() {
            if (flip_coin == 0) {
                face = true;
            } else {
                face = false;
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }i really don't know why the random isn't working. I hope someone would be able to find my errors and instruct me on how to fix them. I would be able to continue the rest of the classes as soon as i got this figured out.
    Oh and can someone teach me how to import this class into a main one? So i can test it out. This is what i have for it.public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
         Coin flipCoin = new Coin();
         for(int i=0;i<6;i++){
         System.out.println(flipCoin.getFace());
    }Many Thanks!
    Edited by: Java_what on Feb 16, 2009 2:26 PM

    Constructors are only executed once. What im confused about is:
    • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    I thought i would flip() into the constructor. Mind helping me out on the whole class because it seems i am clueless about this whole class.
    Edit:
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            flip();
            return flip_coin;
        Coin() {
           //flip();
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }K i reread what you wrote about the constructor and method. So i placed flip() method in getFace(); because its being called in the main(it gives me random numbers). The problem now is following the directions.
    I just dont understand this description. • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    What do you think it means.
    Edited by: Java_what on Feb 16, 2009 4:14 PM

  • URL: newbie needs help with simple programming question!

    Hi everyone,
    Please direct me to a FAQ or other resource, or help me with this problem:
    I want to create a text field (or similar container) that contains both ordinary text AND a URL/hyperlink in it. For example, the following text might appear in the text field:
    "I have many _pictures_ from my vacation"
    where the word "pictures" is actually a hyperlink to a web site, and the other portions of the string are simple text.
    All advice and help is appreciated!
    -Dennis Reda
    [email protected]

    Well here is one way you code do it but if you do alittle research on them links above it will explain how this code works.Well it will explain how jeditorpane and hyperlinklistener work
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.net.*;
    public class b extends javax.swing.JApplet implements HyperlinkListener  {
       JEditorPane field = new JEditorPane();
      public b() {
        Container pane = getContentPane();
        FlowLayout flo = new FlowLayout();
        pane.setLayout(flo);
        field.setPreferredSize(new Dimension(200, 25));
        field.setEditable(false);
        pane.add(field);
        setContentPane(pane);
         String gg1 = "<html><body>I have many_<a    href='http://www.home.com'>pictures</a>_from my vacation</body></html>";
         field.addHyperlinkListener(this);
         field.setContentType("text/html");
         field.setText(gg1);
      public void hyperlinkUpdate(HyperlinkEvent e) {
         if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
          try{
            URL url = new URL("http://www.msn.com");
            getAppletContext().showDocument(url,"_self"); 
            }catch(Exception r) {};
      public void init()  {
         b c = new b();
    ps hope this helped                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help with simple preloader- please

    hello,
    i'm trying to get a simple preloader and progress bar working
    for a swf file. The problem is the main swf. movie starts playing
    under preloader before the preloader is finished. So when the
    preloader has finished you are already well into the main movie.
    (After the movie loops you can see the first part that was missing
    during the preload.) This is the AS that i found from a web site
    (MonkeyFlash), it is AS 3. Below is the script.
    here is a link to the page with the movie:
    http://www.aquatichealings.com/new/
    Also is it not advisable to use AS3 because it will only work
    in Flash 9 and not below and most people may not have 9? Should i
    be starting over in AS2. I had built a AS2 in Flash CS3 but had the
    same problem.
    Please kindly advise on how to make it work correctly. I'd
    really appreciate some help, i've gotten books and scoured the web
    for different methods and i'm afraid i'm a bit of a numb skull with
    Flash and can not seem to get a simple preloader and progress bar
    working correctly. THANKS!
    gregory
    var myRequest:URLRequest = new URLRequest("aquatic-h.swf");
    var myLoader:Loader = new Loader();
    myLoader.load(myRequest);
    myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader);
    myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
    myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showContent);
    var myPreloader:Preloader = new Preloader();
    function showPreloader(event:Event):void {
    addChild(myPreloader);
    myPreloader.x = stage.stageWidth/2;
    myPreloader.y = stage.stageHeight/1.2;
    function showProgress(event:ProgressEvent):void {
    var percentLoaded:Number =
    event.bytesLoaded/event.bytesTotal;
    myPreloader.loading_txt.text = "Loading - " +
    Math.round(percentLoaded * 100) + "%";
    myPreloader.bar_mc.width = 198 * percentLoaded;
    function showContent(event:Event):void {
    removeChild(myPreloader);
    addChild(myLoader);
    }

    ... the pre-loader clip must be accompanied by a "stop"
    perhaps a "stop all sounds", too ActionScript on the action layer
    of the main timeline.
    I keep it simple and ask my prloader to not let the main
    timeline play until the final frame of the movie has loaded. The
    final frame is accompanied by a frame labeled "End" on a layer of
    the main timeline of just labels.

  • Help with a program please

    I am very new to java and working on a program for class.... The program must take a variable x and run it through a given function and the output is a number such as 8.234141... In the end i have to take that result and have two statements print to the screen telling how many digits are on the left and how many are on the right of the decimal. I have done all except the last part the hint given is to convert the double variable into a string variable and use the indexOf() method...here is my program so far. Thanks in advance for your help
    import java.util.Scanner;
    public class Project3 {
    public static void main(String[] args)
    //Declaring my variables
    double x, result, result1, result2, result3;
    //User input of variable 'x'
    Scanner scan = new Scanner (System.in);
    System.out.println("Please enter the value for x: ");
    x = scan.nextDouble();
         //Calculations for final answer
    result1 = (Math.abs(Math.pow(x, 3)-(3 * Math.pow(x, 4))));
    result2 = result1 + (8 * Math.pow(x, 2) + 1);
    result3 = Math.sqrt(result2);
    System.out.println("Result is: " + result3);      
    }

    So let me get this straight... the program is supposed to receive user input, run some arbitrary formula on it, and print the results, and then say how many digits are on the left and right of the decimal?
    If this is the case, I'll give you a few hints:
    ~~
    1) To convert a double to a string , you can do something like this:
    String myString = "" + myDouble; // the "" is a pair of empty quotation marks.
    2) the String class contains the method indexOf(), which searches the string for another string, and returns the index. For example:
    String aString = "Hello, world!";
    int anIndex = aString.indexOf("w");
    anIndex will be equal to the number 7 because the "w" in aString is character number 7 (the first character is number 0, the second is 1, and so on.)
    3) the String class contains the method length() which returns the length of the string.
    ~~
    Think about these things, and if you still can't figure it out, let me know.
    Edited by: Arricherekk on Sep 14, 2008 12:26 PM

  • I need help with a program please

    hi, well, i am trying to make a mine searcher (the game where you have to find all the mines within an array of buttons)anyway,i got everything but i am trying to create a method that allows to unable the buttons surrounding a button that was pressed that didn�t have any mines surrounding it (i am sorry if i am being a little confusing, my english is not very good). anyway, i have the following code for that method, but it isn�t working, please if someone can see what the problem is, send me an answer.
    (alrededores is a method that returns the number of mines surrounding the position auxiliar[i][j])
    public void destapar(boolean [][] auxiliar,int ancho, int largo, int i, int j){
         if(alrededores(auxiliar,ancho,largo,i,j)!=0){
              casilla[i][j].setLabel(""+alrededores(minados,ancho,largo,aux,j));
              casilla[i][j].setEnabled(false);
              casilla[i][j].setBackground(new Color(255,255,255));
              return;}
         else{          
              casilla[i][j].setLabel("");
              casilla[i][j].setEnabled(false);
              casilla[i][j].setBackground(new Color(255,255,255));}
         if(i>0)     
              destapar(auxiliar,ancho,largo,i-1,j);
         if(i<ancho-1)
              destapar(auxiliar,ancho,largo,i+1,j);
         if(j>0)
              destapar(auxiliar,ancho,largo,i,j-1);
         if(j<largo-1)
              destapar(auxiliar,ancho,largo,i,j+1);
    }

    I programmed MineSweeper for my TI-83 back in highschool. You should be able to knock this out of the park.
    i would use a one dimensional array and transform the 2d position.
    have one one-dim array hold the "mines surrounding value" and one other one-dim array hold the state: "not hit" "hit" "exploded" etc.
    I wouldnt dar make the board out of actual buttons. Use a tiled board of .png's or draw the board. Use the mouse location and range and divide by the number of mines to find out where the use clicked.
    For example:
    Board is from x = 100 to x = 200
    Each tile is dx = 10 -> 10 tiles
    user hit mouse location x = 105;
    (105 - 100) / 10 = tilePosX
    for surrounding mines array its just brute force.
    fill the mine field at random (thats why the one-dim array helps among other reasons). Then just iterate through adding up mines surrounding it.

  • New to APEX, help with simple app please

    Need to create a simple app based on 1 box with 4 buttons based to execute sql. Having hard time sifting throught the material need app fast. Sorry for being a block head. Can anyone help or suggest any books to point me in right direction. Need asap. Any help will be appreciated.
    Simple app with one box where username is entered
    --------------------- Enter new users name
    Create user with with added synonyms A
    Create user without synonyms B
    Remove user C
    ADD synonyms to existing user D
    EXIT E
    A = Executes create user command with additional lines of code to add the synonyms
    B = Executes simple create user command
    C = Executes delete user, (sys, system, ect will be excluded
    D = Executes command to add 3 private synonyms
    We are limiting the data they can see if they do not have a synonym.
    Thanks a ton

    Scott,
    Thanks for your reply. This is a DBA create user tool, management wants to provide the application administrator ability to create DBA users only for this database. The application is built so users with certain private synonyms assigned can see data, those without do not. It is a customized COTS app, I would never design like that.
    I do not agree with it, not my decision. I built a shell menu and scripts but that is not GUI enough for this boss. At first It looked like a simple APEX app. I am finding that APEX is more a reporting tool based on objects and I will continue to use it for that. I am learning lots about it so that is cool.
    Andy

  • Help With Java Program Please!

    Greetings,
    I am trying to figure out to write a Java program that will read n lines of text from the keyboard until a blank line is read. And as it read each line, It's suppose to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words
    The total number of words seen in all lines
    I don't know where to begin. Help me please! Thank you very much.

    Man I have to say that this smells like home work.
    Since you have not asked for a cut paste code I tell you what to do
    1. Write a function which take single string as a parameter and break it down to words and return words as a array or string
    (You can use this)
    you will need several variables to keep track of
    The longest string so far
    The Longest word seen so far
    The line that contains the most words and number of words in that line
    The total number of words seen in all lines
    now read lines in a loop if the length is 0 exit (that is your exis condition right)
    otherwise check the length of input string and update "The longest string so far"
    then break down the words and update "The Longest word seen so far", "The line that contains the most words and number of words in that line" and "The total number of words seen in all lines"
    and when you are exiting display the above values

  • Help with simple program

    I am trying to get a program in my CS1 course and am having a hard time, help.. this is what the prof wants>>> Your employer is developing encryption software and wants you to write a Java program that will display all the prime numbers less than N, where N is a number to be entered by a user. In addition to displaying the primes themselves, provide a count of how many there are.

    here is one that i wrote. It does not add them though:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class FindPrimes extends JFrame implements Runnable, ActionListener {
         Thread go;
         JLabel howManyLabel = new JLabel("Quantity: ");
         JTextField howMany = new JTextField("400", 10);
         JButton display = new JButton("Display primes");
         JTextArea primes = new JTextArea(8, 40);
         FindPrimes() {
              super("Find Prime Numbers");
              setSize(400, 300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              BorderLayout bord = new BorderLayout();
              setLayout(bord);
              display.addActionListener(this);
              JPanel topPanel = new JPanel();
              topPanel.add(howManyLabel);
              topPanel.add(howMany);
              topPanel.add(display);
              add(topPanel, BorderLayout.NORTH);
              primes.setLineWrap(true);
              JScrollPane textPane = new JScrollPane(primes);
              add(textPane, BorderLayout.CENTER);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              display.setEnabled(false);
              if (go == null) {
                   go = new Thread(this);
                   go.start();
         public void run() {
              int quantity = Integer.parseInt(howMany.getText());
              int numPrimes = 0;
              // candidate:  the number that might be prime
              int candidate = 2;
              primes.append("First " + quantity + " primes:");
              while (numPrimes < quantity) {
                   if (isPrime(candidate)) {
                        primes.append(candidate + " ");
                        numPrimes++;
                   candidate++;
         public static boolean isPrime(int checkNumber) {
              double root = Math.sqrt(checkNumber);
              for (int i = 2; i <= root; i++) {
                   if (checkNumber % i == 0) {
                        return false;
              return true;
         public static void main(String[] arguments) {
              FindPrimes fp = new FindPrimes();
    }

  • Help with simple animation please

    Hello all. I am writing a class and part of it is to make a stick figure walk across the screen. I have searched for tutorials and all I could seem to find is what I have already done. I have one leg moving on my guy now I am trying to get the whole body to move to the right and start again after it reaches the end of screen. I'll post what I have so far. I have started some new coordinates for the body part (the one long line). It didn't go so well in my applet. Before I go through all this trouble figuring out all these different coordinates trying to move each body part one at a time and keeping them aligned, can somebody tell me if I am on the right track or am I making it harder on myself? I can figure out the movement of a leg because I am only moving one end of it but when it comes to the entire (body) line and the circle, that's where I get a little confused. Is there an easier way of doing this? Am I declaring the variables correctly? Without my crazy body variables, the leg moves just fine, just wanted to show what I am trying to do. Thanks for any help on this.
    import java.applet.*;
    import java.awt.*;
    public class Exercise1 extends Applet
    private int index = 0;
    int[] horiz = {130,120,110,100,90,80,70,60,50};
    int[] vert = {310,310,310,310,310,310,310,310,310};
    int[] bu = {85,110,140,110,170,110}; //move upper body to right?
    int[] bl = {85,310,110,310,140,310};//move lower body to right?
    private int sleep = 200;
    public void start()
    index = 0;
    public void paint(Graphics gr)
    gr.drawOval(30,30,80,80);
    gr.drawLine(85,110,bu[index],bl[index]);
    gr.drawLine(0,310,260,310);
    ++index;
    if(index == horiz.length)
    index = 0;
    gr.setColor(Color.BLACK);
    gr.drawLine(85,210,horiz[index],vert[index]);
    try
    Thread.sleep(sleep);
    catch(InterruptedException e)
    repaint();
    }

    FWIW this is how I would approach this problem: I wouldn''t use hardcoded arrays, I would compute positions.
    1. Add an instance field increment of type int to represent the increment (by how many pixels movement is to be effected in the x-direction i.e. horizontally).
    2. Draw a vertical line to represent the body and move it by "increment" pixels at a time, multiplying increment by -1 each time "body" reached the boundaries of its container. Test that to oblivion.
    3. Add a line for a leg, the top end of which would be the lower end of "body" and the bottom end at the center of the baseline. Test that (the leg would stretch terribly, but there you have it, for the time being)
    4. Start to increment the x position of the bottom of the leg by 2 * increment as soon as the horizontal displacement of the bottom of the leg from the body exceeds a certain limit, and stop as soon as it again exceeds the sme linit in the opposite direction. Test that to oblivion.
    5. Add the other leg, making sure the two legs start ahead and behind the body, so that the partial stick figure appears to walk, not hop.
    6. Modify the condition to reverse the movement when any part of the figure, and not just the body, goes outside the boundaries of the container.
    Then, after getting that working, I would start to think about the head and then the arms. Later I would look into mdifying the routine to give the stick man knees and elbows, then maybe ankles and feet... raise a foot off the ground when taking a step... swing his arms as he walks...
    In a nutshell, do this one part at a time, visualizing where the rest will go, and test test test at each stage so you don't have to backtrack too much.
    A word of advice: don't hardcode movement increments into the body of your code, use variables declared and initialized at the top of the program, where it will be easy to find them and change the values.
    db

  • Hi need help with simple program

    1 System.out.println("Input Number of Question: ");
    2
         3     inputQuestionNum = Integer.parseInt(input.nextLine());
              4     
              5     if(inputQuestionNum>=10) {
              6          System.out.println("Error: Please try again"); //how to return to line 1      
    7 else { 
    8      System.out.println("ok");     
    9 }
    Hi, i am new to java, how to make the program return back to first line when input is more then 10? I do not know how to describe my problem therefore i can't google for solution. thank you in advance.

    The usual approach is to use a do-while loop:Scanner input = new Scanner (System.in);
    int inputQuestionNum;
    do {
        System.out.println ("Input Number of Question: ");
        inputQuestionNum = Integer.parseInt (input.nextLine ());
        if (inputQuestionNum >= 10) {
            System.out.println ("Error: Please try again");
        } else {
                System.out.println ("ok");
        } while (inputQuestionNum >= 10);Ask if that's not clear.
    db

  • Need help with simple program

    I believe that I have everything right except when I get down to the else I want it to return to the while loop. Is there a better way of doing this because it doesn't work for me. Here is the program:
    public class ABCInput
         public static void main(String[] args) throws Exception
              char response;
              System.out.println("Please type a A,B,C to receive a message or a Q to quit");
              response = (char)System.in.read();System.in.read();System.in.read();
              while(response == 'A' || response == 'B' || response == 'C')
                   System.out.println("\"Good Job\"\n\n");
                   System.out.println("Please type a A,B,C to receive a message or a Q to quit");
                   response = (char)System.in.read();System.in.read();System.in.read();
              if(response == 'Q')
                   System.out.println("Thanks for playing");
                   System.exit(0);
              else
                   System.out.println("You have entered an invalid letter. Please try again");
                   response = (char)System.in.read();System.in.read();System.in.read();
    }

    mahugl,
    Try this out.
    public class ABCInput
         public static void main(String[] args) throws Exception
              char response;
              boolean notInvalid = true;
              boolean notFinished = true;
              System.out.println("Please type a A,B,C to receive a message or a Q to quit");
              response = (char)System.in.read();System.in.read();System.in.read();
              while(notFinished == true)
                   while(notInvalid == true)
                        if(response == 'A' || response == 'B' || response == 'C' || response == 'Q' || response == 'a' || response == 'b' || response == 'c' || response == 'q')
                             notInvalid = false;
                        else
                             System.out.println("You have entered an invalid letter. Please try again");
                             response = (char)System.in.read();System.in.read();System.in.read();
                   if(response == 'Q' || response == 'q')
                        notFinished = false;
                   else
                        System.out.println("\"Good Job\"\n\n");
                        System.out.println("Please type a A,B,C to receive a message or a Q to quit");
                        response = (char)System.in.read();System.in.read();System.in.read();
                        notInvalid = true;
              System.out.println("Thanks for playing");
              System.exit(0);
    }jerryrika

  • Help with simple jsp please

    Hi,
    I would like to know how to create a simple jsp to display some data from the database. I was able to create a bean to display the data from a table using the wizard. How do I put this bean's content into the jsp?
    Thanks,
    Charles Li

    Even better are the online tutorials that will take you step by step:
    http://www.oracle.com/technology/obe/obe9051jdev/index.htm
    Try the ADF Workshop one - it will show you most of what you need.

  • Need help to draw a graph from the output I get with my program please

    Hi all,
    I please need help with this program, I need to display the amount of money over the years (which the user has to enter via the textfields supplied)
    on a graph, I'm not sure what to do further with my program, but I have created a test with a System.out.println() method just to see if I get the correct output and it looks fine.
    My question is, how do I get the input that was entered by the user (the initial deposit amount as well as the number of years) and using these to draw up the graph? (I used a button for the user to click after he/she has entered both the deposit and year values to draw the graph but I don't know how to get this to work?)
    Please help me.
    The output that I got looked liked this: (just for a test!) - basically this kind of output must be shown on the graph...
    The initial deposit made was: 200.0
    After year: 1        Amount is:  210.00
    After year: 2        Amount is:  220.50
    After year: 3        Amount is:  231.53
    After year: 4        Amount is:  243.10
    After year: 5        Amount is:  255.26
    After year: 6        Amount is:  268.02
    After year: 7        Amount is:  281.42
    After year: 8        Amount is:  295.49
    After year: 9        Amount is:  310.27
    After year: 10        Amount is:  325.78
    After year: 11        Amount is:  342.07
    After year: 12        Amount is:  359.17
    After year: 13        Amount is:  377.13
    After year: 14        Amount is:  395.99
    After year: 15        Amount is:  415.79
    After year: 16        Amount is:  436.57
    After year: 17        Amount is:  458.40And here is my code that Iv'e done so far:
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Math;
    import java.text.DecimalFormat;
    public class CompoundInterestProgram extends JFrame implements ActionListener {
        JLabel amountLabel = new JLabel("Please enter the initial deposit amount:");
        JTextField amountText = new JTextField(5);
        JLabel yearsLabel = new JLabel("Please enter the numbers of years:");
        JTextField yearstext = new JTextField(5);
        JButton drawButton = new JButton("Draw Graph");
        public CompoundInterestProgram() {
            super("Compound Interest Program");
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            amountText.addActionListener(this);
            yearstext.addActionListener(this);
            JPanel panel = new JPanel();
            panel.setBackground(Color.white);
            panel.add(amountLabel);
            amountLabel.setToolTipText("Range of deposit must be 20 - 200!");
            panel.add(amountText);
            panel.add(yearsLabel);
            yearsLabel.setToolTipText("Range of years must be 1 - 25!");
            panel.add(yearstext);
            panel.add(drawButton);
            add(panel);
            setVisible(true);
            public static void main(String[] args) {
                 DecimalFormat dec2 = new DecimalFormat( "0.00" );
                CompoundInterestProgram cip1 = new CompoundInterestProgram();
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.getContentPane().add(new GraphPanel());
                f.setSize(500, 500);
                f.setLocation(200,200);
                f.setVisible(true);
                Account a = new Account(200);
                System.out.println("The initial deposit made was: " + a.getBalance() + "\n");
                for (int year = 1; year <= 17; year++) {
                      System.out.println("After year: " + year + "   \t" + "Amount is:  " + dec2.format(a.getBalance() + a.calcInterest(year)));
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
    class Account {
        double balance = 0;
        double interest = 0.05;
        public Account() {
             balance = 0;
             interest = 0.05;
        public Account(int deposit) {
             balance = deposit;
             interest = 0.05;
        public double calcInterest(int year) {
               return  balance * Math.pow((1 + interest), year) - balance;
        public double getBalance() {
              return balance;
    class GraphPanel extends JPanel {
        public GraphPanel() {
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.red);
    }Your help would be much appreciated.
    Thanks in advance.

    watertownjordan wrote:
    http://www.jgraph.com/jgraph.html
    The above is also good.Sorry but you need to look a bit more closely at URLs that you cite. What the OP wants is a chart (as in X against Y) not a graph (as in links and nodes) . 'jgraph' deals with links and nodes.
    The best free charting library that I know of is JFreeChart from www.jfree.org.

Maybe you are looking for

  • Invoice for Local contract.

    The process in ECC system  1) create a contract 2) Create Release Order 3) Post the invoice against Release order, we won't be able to post the invoice against the contract . In SRM system , is it possible to post the invoice against the local contra

  • Question about Stacking

    Hello Everyone, I have a quick question about stackwise plus technology. I would like to confirm that there is no redundancy at the ethernet switch port in terms of a physical problem. The reason I ask is that we are deploying stacked switches shortl

  • Faces-config as file resource?

    Is it possible to use a faces configuration file stored on the server, instead of in the WEB-INF directory? I'd like to store some server specific settings in our dev and QA environments and have my JSF app look them up something like this: Web.xml <

  • Collapse/Expand in Queries

    Hello, I wish to create a query that gives the user the ability of expanding and collapsing data. I would like to display the invoices grouped by customer id and show the total amount for each customer. Optionally, the user could expand that customer

  • Variable accessed before it is bound!

    Hi, I have an XSL which reads data from an XML and using the attribute values from the XML,it does a certain processing. My XSL is able to read the XML.My XML has some 20 elements and it needs to read each element and process the data. But my XSL is