Please answer the following questions in the java language. 1. Create a method (
ID: 3696267 • Letter: P
Question
Please answer the following questions in the java language.
1. Create a method (function) with an int type parameter. This function will print out prime numbers on screen range from 0 to the parameter value. The function will return the number of the prime numbers. Use main() method to test if your function works well.
2. Read and try to understand the following example:
Summarize the using of Scanner: how to read data from keyboard, how to read data from a file,
and how to read data from a web page.
3. What’s the output of the following program:
public class NewClass
{
public static void main(String[] args)
{
String s1 = "Computer Science";
int x = 262;
String s2 = s1 + " " + x;
String s3 = s2.substring(10,17);
String s4 = " is fun";
String s5 = s2 + s4;
System.out.println("s1: " + s1.replace("e", "E"));
System.out.println("s2: " + s2.toLowerCase());
System.out.println("s3: " + s3);
System.out.println("s4: " + s4.toUpperCase());
System.out.println("s5: " + s5);
//showing effect of precedence
x = s1.indexOf("e",9);
int y = s1.indexOf("e");
String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";
System.out.println("s6: " + s6);
System.out.println("s7: " + s7);
System.out.println("s8: " + s8);
}
}
Explanation / Answer
1.
import java.util.*;
class prime
{
public static void Prime(int n1)
{
int i,j,a,n;
for(j=0;j<=n1;j++
{
n=j;
for(i=2;i<n;i++)
{
a=n%i;
if(a==0)
{
break;
}
}
if(i==n)
{
System.out.println(n);
}
}
}
public static void main(String args[])
{
Scanner scan= new Scanner(System.in);
int n=scan.nextInt();
Prime(n);
}
}
3.
s1: ComputEr SciEncE
s2: computer science 262
s3: Science
s4: SCIENCE IS FUN
s5: Computer Science 262 Science is fun
s6: 20total
s7: total20
s8: 20total