Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CSE 292 Java Programming
Professor Tong Lai Yu
Homework 5
Santiago Campero
1) 
Follow the tutorial of the link, 
http://developer.android.com/resources/tutorials/views/hello-gridview.html 
to create the Grid View of the HelloWorld example in Android. Replace some of the 
icons provided by the site by your own icons. Choose Android version 2.3.3. 
Program Run
ImageAdapter.Java
package com.example.hellogridview;
import android.content.Context;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import android.view.ViewGroup;
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public ImageAdapter(Context c) {
        mContext = c;
    }
    public int getCount() {
        return mThumbIds.length;
    }
    public Object getItem(int position) {
        return null;
    }
    public long getItemId(int position) {
        return 0;
    }
    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }
    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
    };
}
MainActivity.Java
package com.example.hellogridview;
import android.os.Bundle;
import android.app.Activity;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
import android.view.*;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));
    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) 
{
            Toast.makeText(MainActivity.this, "" + position, 
Toast.LENGTH_SHORT).show();
        }
    });
}
}
Main.XML


2) 
Follow the instructions of the following document, which is from your textbook, 
Tip Calculator 
to create the Tip Calculator. The following is the source code of the problem:
TipCalculator.zip
Program Run
TipCalculator.Java
// TipCalculator.java
// Calculates bills using 5, 10, 15 and custom percentage tips.
package com.deitel.tipcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
// main Activity class for the TipCalculator
public class TipCalculator extends Activity 
{
   // constants used when saving/restoring state
   private static final String BILL_TOTAL = "BILL_TOTAL";
   private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
   
   private double currentBillTotal; // bill amount entered by the user
   private int currentCustomPercent; // tip % set with the SeekBar
   private EditText tip10EditText; // displays 10% tip
   private EditText total10EditText; // displays total with 10% tip
   private EditText tip15EditText; // displays 15% tip
   private EditText total15EditText; // displays total with 15% tip
   private EditText billEditText; // accepts user input for bill total
   private EditText tip20EditText; // displays 20% tip
   private EditText total20EditText;  // displays total with 20% tip
   private TextView customTipTextView; // displays custom tip percentage
   private EditText tipCustomEditText; // displays custom tip amount
   private EditText totalCustomEditText; // displays total with custom tip
   // Called when the activity is first created.
   @Override
   public void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState); // call superclass's version
      setContentView(R.layout.main); // inflate the GUI
      // check if app just started or is being restored from memory
      if ( savedInstanceState == null ) // the app just started running
      {
         currentBillTotal = 0.0; // initialize the bill amount to zero
         currentCustomPercent = 18; // initialize the custom tip to 18%
      } // end if
      else // app is being restored from memory, not executed from scratch
      {
         // initialize the bill amount to saved amount
         currentBillTotal = savedInstanceState.getDouble(BILL_TOTAL); 
         // initialize the custom tip to saved tip percent       
         currentCustomPercent = 
            savedInstanceState.getInt(CUSTOM_PERCENT); 
      } // end else
      
      // get references to the 10%, 15% and 20% tip and total EditTexts
      tip10EditText = (EditText) findViewById(R.id.tip10EditText);
      total10EditText = (EditText) findViewById(R.id.total10EditText);
      tip15EditText = (EditText) findViewById(R.id.tip15EditText);
      total15EditText = (EditText) findViewById(R.id.total15EditText);
      tip20EditText = (EditText) findViewById(R.id.tip20EditText);
      total20EditText = (EditText) findViewById(R.id.total20EditText);
      
      // get the TextView displaying the custom tip percentage
      customTipTextView = (TextView) findViewById(R.id.customTipTextView);
      
      // get the custom tip and total EditTexts 
      tipCustomEditText = (EditText) findViewById(R.id.tipCustomEditText);
      totalCustomEditText = 
         (EditText) findViewById(R.id.totalCustomEditText);
      // get the billEditText 
      billEditText = (EditText) findViewById(R.id.billEditText);
      // billEditTextWatcher handles billEditText's onTextChanged event
      billEditText.addTextChangedListener(billEditTextWatcher);
      
      // get the SeekBar used to set the custom tip amount
      SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
      customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
   } // end method onCreate
   // updates 10, 15 and 20 percent tip EditTexts
   private void updateStandard() 
   {
      // calculate bill total with a ten percent tip
      double tenPercentTip = currentBillTotal * .1;
      double tenPercentTotal = currentBillTotal + tenPercentTip;
      // set tipTenEditText's text to tenPercentTip
      tip10EditText.setText(String.format("%.02f", tenPercentTip));
      // set totalTenEditText's text to tenPercentTotal
      total10EditText.setText(String.format("%.02f", tenPercentTotal));
      // calculate bill total with a fifteen percent tip
      double fifteenPercentTip = currentBillTotal * .15;
      double fifteenPercentTotal = currentBillTotal + fifteenPercentTip;
      // set tipFifteenEditText's text to fifteenPercentTip
      tip15EditText.setText(String.format("%.02f", fifteenPercentTip));
      // set totalFifteenEditText's text to fifteenPercentTotal
      total15EditText.setText(
         String.format("%.02f", fifteenPercentTotal));
      // calculate bill total with a twenty percent tip
      double twentyPercentTip = currentBillTotal * .20;
      double twentyPercentTotal = currentBillTotal + twentyPercentTip;
      // set tipTwentyEditText's text to twentyPercentTip
      tip20EditText.setText(String.format("%.02f", twentyPercentTip));
      // set totalTwentyEditText's text to twentyPercentTotal
      total20EditText.setText(String.format("%.02f", twentyPercentTotal));
   } // end method updateStandard
   // updates the custom tip and total EditTexts
   private void updateCustom() 
   {
      // set customTipTextView's text to match the position of the SeekBar
      customTipTextView.setText(currentCustomPercent + "%");
      // calculate the custom tip amount
      double customTipAmount = 
         currentBillTotal * currentCustomPercent * .01;
      // calculate the total bill, including the custom tip
      double customTotalAmount = currentBillTotal + customTipAmount;
      // display the tip and total bill amounts
      tipCustomEditText.setText(String.format("%.02f", customTipAmount));
      totalCustomEditText.setText(
         String.format("%.02f", customTotalAmount));
   } // end method updateCustom
   // save values of billEditText and customSeekBar
   @Override
   protected void onSaveInstanceState(Bundle outState)
   {
      super.onSaveInstanceState(outState);
      
      outState.putDouble(BILL_TOTAL, currentBillTotal);
      outState.putInt(CUSTOM_PERCENT, currentCustomPercent);
   } // end method onSaveInstanceState
   
   // called when the user changes the position of SeekBar
   private OnSeekBarChangeListener customSeekBarListener = 
      new OnSeekBarChangeListener() 
   {
      // update currentCustomPercent, then call updateCustom
      @Override
      public void onProgressChanged(SeekBar seekBar, int progress,
         boolean fromUser) 
      {
         // sets currentCustomPercent to position of the SeekBar's thumb
         currentCustomPercent = seekBar.getProgress();
         updateCustom(); // update EditTexts for custom tip and total
      } // end method onProgressChanged
      @Override
      public void onStartTrackingTouch(SeekBar seekBar) 
      {
      } // end method onStartTrackingTouch
      @Override
      public void onStopTrackingTouch(SeekBar seekBar) 
      {
      } // end method onStopTrackingTouch
   }; // end OnSeekBarChangeListener
   // event-handling object that responds to billEditText's events
   private TextWatcher billEditTextWatcher = new TextWatcher() 
   {
      // called when the user enters a number
      @Override
      public void onTextChanged(CharSequence s, int start, 
         int before, int count) 
      {         
         // convert billEditText's text to a double
         try
         {
            currentBillTotal = Double.parseDouble(s.toString());
         } // end try
         catch (NumberFormatException e)
         {
            currentBillTotal = 0.0; // default if an exception occurs
         } // end catch 
         // update the standard and custom tip EditTexts
         updateStandard(); // update the 10, 15 and 20% EditTexts
         updateCustom(); // update the custom tip EditTexts
      } // end method onTextChanged
      @Override
      public void afterTextChanged(Editable s) 
      {
      } // end method afterTextChanged
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
         int after) 
      {
      } // end method beforeTextChanged
   }; // end billEditTextWatcher
} // end class TipCalculator
   
3) The following are provided:
• Lines.java   
• LinesJPanel  
Follow the comments '/* .. */' to finish the programs.
Program Run
Lines.Java
package edu.CSE292.HW5c;
//Lab Exercise 2 Solution: Lines.java
//This program draws lines of different colors
import java.awt.Color;
import javax.swing.JFrame;
public class Lines
{
public static void main( String args[] )
{
   // create frame for LinesJPanel
   JFrame frame = new JFrame( "Lines" );
   frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   LinesJPanel linesJPanel = new LinesJPanel(); 
   frame.add( linesJPanel ); // add linesJPanel to frame
   frame.setSize( 300, 300 ); // set frame size
   frame.setVisible( true ); // display frame
} // end main
} // end class Lines
LinesJPanel.Java
package edu.CSE292.HW5c;
//Lab Exercise 2 Solution: LinesJPanel.java
//This program draws lines of different colors
import java.awt.Color;
import java.awt.BasicStroke;
import java.awt.geom.Line2D;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import javax.swing.JPanel;
public class LinesJPanel extends JPanel 
{
private Color colors[] = { Color.GREEN, Color.CYAN, Color.YELLOW, 
        Color.DARK_GRAY, Color.RED, Color.ORANGE,
        Color.GRAY, Color.PINK, Color.MAGENTA };
// create 10 lines
public void paintComponent( Graphics g )
{
   super.paintComponent( g );
   setBackground( Color.BLACK ); // set JPanel background
   Random random = new Random(); // get random number generator
   int thickness = 1;  // default thickness
   int colorChoice = 0;  // default color green
   int lineLenght = 1;  //default lenght
   
   // create 2D by casting g to Graphics 2D
   Graphics2D g2d = ( Graphics2D ) g;
   for ( int y = 60; y < 250; y += 20 ) 
   {
      // choose a random color from array
      /* Randomly choose an element of array colors and pass it to Graphics2D 
         method setColor to specify the drawing color */
      //pickrandom integerfrom0to8
        colorChoice = random.nextInt(8 );
        g2d.setPaint(colors[colorChoice]);
      // choose a random thickness from 1-20
      /* Use Graphics2D method setStroke to randomly set the thickness of a line */
      //pickrandom integerfrom1to20
        thickness = 1+random.nextInt(20 );
        g2d.setStroke(new BasicStroke(thickness) );
      // choose a random length and draw line
      /* Create a random length line and use Graphics2D method draw
         to display the lines*/
         lineLenght  = 1+random.nextInt(300 );
         g2d.draw(new Line2D.Double(0, y, lineLenght, y ) );
   } // end for
} // end method paintComponent
} // end class LinesJPanel
4) Textbook, P.763, #17.8 (Telephone Number Word Generation) 
Standard telephone keypads contain the digits zero through nine. The numbers two 
through nine each have three letters associated with them as shown below:
Digit   Letter   Digit   Letter   Digit   Letter   
2 A B C 5 J K L 8 T U V 
3 D E F 6 M N O 9 W X Y 
4 G H I 7 P R S    
For ease of memorization, people develop seven-letter words that correspond to 
their phone numbers. For example, one might use NUMBERS to represent 686-
2377.
Every seven-letter phone number corresponds to many different seven-letter words, 
many of them unrecognizable. Write a program that, given a seven-digit number, 
uses a PrintStream object to write to a file every possible seven-letter word 
combination corresponding to that number. There are 2,187 (37 such combinations. 
Avoid phone numbers with digits 0 and 1.
Program Run
PhoneNames.Java
package edu.CSE292.HW5d;
//public class PhoneNames {
import java.util.LinkedList;
import java.util.List;
public class PhoneNames {  
    // Number-to-letter mappings in order from zero to nine
    public static String mappings[][] = {
        {"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
        {"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"}, 
        {"T", "U", "V"}, {"W", "X", "Y", "Z"}
    };
    
    public static void generateCombosHelper(List combos, 
            String prefix, String remaining) {
        // The current digit we are working with
        int digit = Integer.parseInt(remaining.substring(0, 1));
        if (remaining.length() == 1) {
            // We have reached the last digit in the phone number, so add 
            // all possible prefix-digit combinations to the list
            for (int i = 0; i < mappings[digit].length; i++) {
                combos.add(prefix + mappings[digit][i]);
            }
        } else {
            // Recursively call this method with each possible new 
            // prefix and the remaining part of the phone number.
            for (int i = 0; i < mappings[digit].length; i++) {
                generateCombosHelper(combos, prefix + mappings[digit][i], 
                        remaining.substring(1));
            }
        }
    }
    public static List generateCombos(String phoneNumber) {
        // This will hold the final list of combinations
        List combos = new LinkedList();
        // Call the helper method with an empty prefix and the entire 
        // phone number as the remaining part.
        generateCombosHelper(combos, "", phoneNumber);
        return combos;
    }
    public static void main(String[] args) {
        String phone = "3456789";
        List combos = generateCombos(phone);
        for (String s : combos) {
            System.out.println(s);
        }
    }
}