Q1)
1:public class StringLength {
2: public static void main(String[] args) {
3: int sum = 0;
4: for(int i = 0; i < args.length; i++) {
5: sum+=args[i].length();
6: }
7: System.out.println(sum);
8: }
9:}
Q2)
1:public class RemoveDigit {
2: public static String removeDigit(String s) {
3: char[] array = s.toCharArray();
4: String temp = "";
5: for(int i = 0; i < array.length; i++) {
6: if(!Character.isDigit(array[i])) {
7: temp = temp + array[i];
8: }
9: }
10: return temp;
11: }
12:
13: public static void main(String[] args) {
14: for(int i = 0; i < args.length; i++) {
15: System.out.print(removeDigit(args[i]) + " ");
16: }
17: }
18:}
Q3) string.length() and array.length are correct.
Q4) Refer to my notes.
Q5) (i),(iii),(iv). are correct.
(ii) begins with a digit, which is not allowed
(v) and (vi) contains characters other than _, $
(vii) is a reserved keyword.
Q6) 101
Q7) Refer to my notes.
Q8)
// import statements
import java.awt.*;
import javax.swing.*;
public class ShowShape extends JFrame {
private String shape;
// your constructor
public ShowShape(String shape) {
this.shape = shape;
setBackground(Color.white);
}
// paint method
public void paint(Graphics g) {
if(shape.equals("circle")) {
g.setColor(Color.red);
g.fillOval(50,50,100,100);
} else if(shape.equals("square")) {
g.setColor(Color.yellow);
g.fillRect(50,50,100,100);
}
}
// main method
public static void main(String[] args) {
ShowShape s;
s = new ShowShape(args[0]);
s.setSize(200,200);
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
s.setVisible(true);
}
}
Question 9)
public class Match{
public static void main(String[] args) {
if(args.length >= 2) {
char[] charArray = args[0].toCharArray();
boolean done;
for(int i = 1; i < args.length; i++) {
done = false;
for(int j = 0; j< charArray.length; j++) {
if(args[i].indexOf(charArray[j]) != -1) {
if(!done) {
done = true;
System.out.print(args[i] + " ");
}
}
}
}
}
}
}
A solution using break
public class Match{
public static void main(String[] args) {
if(args.length >= 2) {
char[] charArray = args[0].toCharArray();
for(int i = 1; i < args.length; i++) {
for(int j = 0; j<charArray.length; j++) {
if(args[i].indexOf(charArray[j]) != -1) {
System.out.print(args[i] + " ");
break;
}
}
}
}
}
}