How to loop this server program [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
I cant seem to loop this server program, when I was at the Command prompt the code didn't end and i cant still type but the text that I want to loop wont show.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class serverExer2 {
public static void main(String[] args) {
//telnet localhost 2000
int port = 2000;
Scanner input = new Scanner(System.in);
String YN = "";
do {
try (ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
BufferedReader streamRdr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter streamWtr = new PrintWriter(clientSocket.getOutputStream(), true)) {
// server sends message to client
streamWtr.println("What is your name? ");
// server accepts input from client
String name = streamRdr.readLine();
int age;
while (true) {
streamWtr.println("What is your age? ");
try {
age = Integer.parseInt(streamRdr.readLine());
if (age <= 0) {
throw new NumberFormatException();
} else {
break;
}
} catch (NumberFormatException nfe) {
// println method will auto flush
streamWtr.println("Please enter a valid age.");
}
}
if (age >= 18) {
streamWtr.println(name + ", you may exercise your right to vote!");
} else {
streamWtr.println(name + ", you are still too young to vote!");
}
streamWtr.println("Continue? Y or N: ");
YN = input.nextLine();
} catch (Exception e) {
e.printStackTrace();
}
} while (YN.equalsIgnoreCase("Y"));
}
}
Tried While loop, do while loop but still no pregress.

Related

Hashmap iteration for a grading system [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
import java.util.*;
import java.util.Map.Entry;
public class fff2 {
public static void main(String[] args) throws NullPointerException{
try {
LinkedHashMap<String, Integer> score = new LinkedHashMap<String,Integer>();
score.put("Fail",39);
score.put("Third Class", 49);
score.put("Second Class, Division 2",59);
score.put("Second Class, Division 1",69);
score.put("First Class",70);
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
int mark = scan.nextInt();
if(mark >100 && mark < 0) {
System.out.println("Invalid Input: out of range.");
}
for(String i: score.keySet()) {
if(mark< score.get(i)) {
System.out.println("You got a "+i);
break;
}
}
}
catch(InputMismatchException e) {
System.out.println("Invalid Input, program terminating");
}
}
So I am trying to make a grading system but it isn't working can i have some help please? I am trying to make it so that a mark of 40 is a pass as a third class but i want to use a hashmap to challenge myself as opposed to the switch case.
I assume you want something like this:
LinkedHashMap<String, Integer> score = new LinkedHashMap<String,Integer>();
score.put("Fail",39);
score.put("Third Class", 49);
score.put("Second Class, Division 2",59);
score.put("Second Class, Division 1",69);
score.put("First Class",70);
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
String keyScore = scan.nextString();
System.out.println(score.getOrDefault(keyScore, "Invalid Input: key not in map"));
where on input you put one of the keys from the map, and not the value.
Replace
score.put("First Class",70);
with
score.put("First Class",100);
and also replace
if(mark< score.get(i)) {
with
if(mark<= score.get(i)) {
import java.util.*;
public class fff {
public static void main(String[] args) throws NullPointerException{
try {
LinkedHashMap<Integer, String> score = new LinkedHashMap<Integer,String>();
score.put(70, "First class");
score.put(59, "Second Class, Division 1");
score.put(49, "Second Class, Divison 2");
score.put(39, "Third Class");
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
int mark = scan.nextInt();
if(mark >100 && mark < 0) {
System.out.println("Invalid Input: out of range.");
}
for(Integer i: score.keySet()) {
if(mark <= 39) {
System.out.println("You got a Fail");
System.exit(0);
}
if(mark>=i) {
System.out.println("You got a "+score.get(i));
break;
}
}
}
catch(InputMismatchException e) {
System.out.println("Invalid Input, program terminating");
}
}
}
This is my final code and it now works.

how can i make a write function that not in the main [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I have a code:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class Tutorial6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choose;
System.out.println("Enter your choice: ");
choose = scanner.nextInt();
if(choose == '1'){
write();
}
else{
read();
}
}
public static void write() throws IOException, ClassNotFoundException{
PrintWriter output = new PrintWriter(new FileWriter("users.txt", true));
Scanner scanner = new Scanner(System.in);
String name, address, ages;
System.out.println("Enter your name: ");
name = scanner.nextLine();
System.out.println("Enter your address: ");
address = scanner.nextLine();
System.out.println("Enter your ages: ");
ages = scanner.nextLine();
output.println(name + " " + address + " " + ages + "\n");
output.flush();
output.close();
}
public static void read(){
Scanner input = new Scanner (new File("users.txt"));
while (input.hasNext()) {
System.out.println(input.nextLine());
}
input.close();
}
}
it have an error called Unhandled exception type. How can I fix it, I have tried to put the write and read function in different java class and it work fine. But I want it to work like a register text interface app.
Surround write function call with try-catch block
if(choose == '1'){
try{
write();
} catch(Exception e){
// handle exception here
}
} else {
read();
}

Java - Getting NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem with where I am getting a NullPointerException on line 59 of my code.
The program's purpose is to prompt the user for the file location (which has the digits of PI). The program should then accept any number of digits (say k digits) via the Scanner class. Then, the program must read k digits of PI from the file. Using the Scanner class, the program should then obtain a number for 0-9 from a user and print the first and last position in which it appears and also the number of times it appears. Only digits after the decimal point are to be considered. The program should be able to accept 100,000 digits of PI.
The sample output of the code is below:
Give the location of the file:
C:\Users\Joe\Desktop\pi.txt
Number of digits of PI to parse:
10
Give any number between 0-9:
1
1 appears 2 times
First position in which appears: 1
Last position in which appears: 3
Any help would be much appreciated.
Below is my code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Problem2 {
#SuppressWarnings("null")
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Joe\\Desktop\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
System.out.println("Give any number between 0-9: ");
String searchnum = input.next();
int count = 0;
for(int i = 1; i < parsenum - 1; i++) {
if(searchnum == stringarray[i]) {
count++;
}
else count++;
}
System.out.println(searchnum + " appears " + count + " time(s)");
for(int i = 1; i < parsenum - 1; i++) {
System.out.print(stringarray[i]);
}
System.out.println();
System.out.println("First position in which " + searchnum + " appears: " + stringinput.indexOf(searchnum));
System.out.println("Second position in which " + searchnum + " appears: " + stringinput.lastIndexOf(searchnum));
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
e.printStackTrace();
System.exit(0);
}
finally {
reader.close();
}
}
}
while((stringinput = reader.readLine()) != null)
The above while loop will run untill reader.readLine is null and so will be stringinput.
Now after the while loop your using stringinput:
stringinput.indexOf(searchnum)
stringinput.lastIndexOf(searchnum)
and thus getting the NullPointerException.

Output keeps on running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the output keep on running? When I run this program, and I enter the in the output, it keeps running, and doesn't let me enter any more numbers. Why is this happening?
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionTest2
{
public static void main(String[] args)
{
Scanner st = new Scanner(System.in);
int ab, bd, cde;
ab = bd = cde = 0;
boolean infinite, in;
do
{
System.out.println("Enter the numbers to divide");
infinite = false;
in = true;
try
{
ab = st.nextInt();
bd = st.nextInt();
infinite = false;
in = true;
}
catch (InputMismatchException e)
{
System.out.println("Invalid input");
in = true;
}
finally
{
if (in)
{
try
{
System.out.println("I am in try block before exception");
cde = ab / bd;
System.out.println("I am in try block after exception");
}
catch (Exception e)
{
infinite = true;
}
finally
{
if (!infinite)
{
System.out.println("Answer is " + cde);
};
}
}
}
}
while (cde != 100);
st.close();
}
}
problem:
ab = st.nextInt();
When you input a String on it I wont get consumed by the nextInt and no one will thus giving you infinite loop
solution:
You need to consume those characters that you inputted in your catch block to avoid the infinite loop
sample:
catch (InputMismatchException e) {
System.out.println("Invalid input");
st.nextLine();
in=true;
}

How to display asterisk for input in Java? [duplicate]

This question already has answers here:
Masking password input from the console : Java
(5 answers)
Closed 8 years ago.
I need to write a little program in Java that asks a person to enter a Pin Code.
So I need the Pin to be hidden with asterisks (*) instead of the numbers. How can I do that?
So far, this is my code :
import java.util.Scanner;
import java.io.*;
public class codePin {
public static void main(String[] args){
int pinSize = 0;
do{
Scanner pin = new Scanner(System.in);
System.out.println("Enter Pin: ");
int str = pin.nextInt();
String s = new Integer(str).toString();
pinSize = s.length();
if(pinSize != 4){
System.out.println("Your pin must be 4 integers");
} else {
System.out.println("We're checking if Pin was right...");
}
}while(pinSize != 4);
}
}
Actually this program works for now, but I want to add a functionality to display Pin like "* * * " or " * *" etc... (in the console when the Person enters is own Pin).
I found something to entirely hide the Pin, but I do not want this. I want the Pin with asterisks
Any ideas ? Thanks
Something like this:
import java.io.*;
public class Test {
public static void main(final String[] args) {
String password = PasswordField.readPassword("Enter password:");
System.out.println("Password entered was:" + password);
}
}
class PasswordField {
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
et.stopMasking();
return password;
}
}
class EraserThread implements Runnable {
private boolean stop;
public EraserThread(String prompt) {
System.out.print(prompt);
}
public void run () {
while (!stop){
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}
The Console class is the correct way to read passwords from the command line. However, it doesn't print asterisks, as that would leak information in general (not in the case where a PIN is known to be 4 digits). For something like that, you'd might need a curses library.

Categories

Resources