Syntax error on token(s), misplaced construct(s) Code Help Needed - java

I use eclipse to help me code & I have been having issues with the error message "Syntax error on token(s), misplaced construct(s)" coming up, I'm not entirely sure what is wrong with my code.
The goal of this code is to write a program where a user enters their name and age and the program checks to see the age is between 0 and 125. If not, the program shows an error code (use Exception Class)
Here is my current code: Errors are showing up in lines 1 and 4
public class ThreadsUnitProject1 {
import java.lang.String;
import java.io.*;
public static void main(String args[]);
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try {
name = br.readLine();
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e) {
System.out.println("Error: " + e);
System.exit(1);
}
finally {
System.out.println("No errors found.");
}
}
}
}
Thank you thank you thank you for all of your help, I have been coding for awhile, but I'm new to Java.
Thanks again!
-Kristen

public static void main(String args[]) is a method it needs to create a block with curly braces. It doesn't contain the block in the ThreadsUnitProject1 class.
public static void main(String args[]){}
Also the import statements should be outside the class declaration.
Full Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThreadsUnitProject1 {
public static void main(String args[]) {
}
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
try {
name = br.readLine();
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
} finally {
System.out.println("No errors found.");
}
}
}
}

Use {} after public static void main(String args[]), not ;.

Related

Java: issue calculating average from txt file

Hello everybody first post on here!
i'm currently having some issues with my readfromfile() to calculate an average my issue is that its printing the ten numbers "stuck together"
like 12345678910 i dont understand how i can calculate an average like this i tried token/10 and it returns 0000000000
any suggestions getting an average from this mess?
i tried returning token with %n%s which looks better but still when i divide by 10 it doesnt give me a correct number what am i doing wrong
package average;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class average {
private static Formatter output;
private static Scanner input;
public static void main(String[] args) {
openFileWrite();
writeToFile();
closeFile();
openFileRead();
readFromFile();
closeFileRead();
}
public static void openFileRead() { // gets file for "read"
try {
input = new Scanner(Paths.get("Numbers.txt"));
} catch (IOException e) {
System.out.println("Unable to read file");
}
}
public static void openFileWrite() { // gets file for "write"
try {
output = new Formatter("Numbers.txt");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file");
}
}
public static void readFromFile() {
while (input.hasNextInt()) {
int token = input.nextInt();
System.out.print(token);
}
}
public static void writeToFile() {
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers");
try {
for (int i = 0; i < 10; i++) {
System.out.println("Another Number Please");
int total = input.nextInt();
output.format("%s%n", total);
}
} catch (InputMismatchException e) {
System.out.println("Please do not enter any letters");
writeToFile();
}
}
//required to close file for write
public static void closeFile() {
output.close();
}
//required to close file for read
public static void closeFileRead() {
input.close();
}
}
Just change your readFromFile method as:-
public static void readFromFile() {
double average = 0;
while (input.hasNextInt()) {
int token = input.nextInt();
average+=token;
}
System.out.println("Average ="+average/10);
}

How to stop NoSuchElementException error from this part of the code? [duplicate]

This question already has answers here:
NoSuchElementException after closing system.in
(1 answer)
Scanner throwing NoSuchElementException
(2 answers)
NoSuchElementException Issue
(1 answer)
Closed 5 years ago.
This is a section of my code from a project that is giving an error. I am practicing encapsulation, but, cannot figure out why I am getting this error when I am setting values inside the Array-list.
There are two classes
1) Create_accountant
2) Adminstoreroom
Both of them are under same package: com.admin
package com.admin;
import java.util.InputMismatchException;
import java.util.Scanner;
class Create_accountant {
Adminstoreroom admin = new Adminstoreroom();
void Creating() {
System.out.println();
System.out.println("\t\t\t\t Create New Accoutant");
System.out.println();
name();
pass();
}
void name() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her name: \t");
String name = null;
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the name again.");
name();
}
catch(Exception e) {
System.out.println("Here is the main problem " + e);
}
admin.setAccName(name);
input.close();
}
private void pass() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her password: \t");
try {
admin.setAccPassword(input.nextLine());
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the password again.");
pass();
}
catch(Exception e) {
System.out.println("Here is the main problem");
}
input.close();
}
The problem is inside the 2 try blocks.
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
Both of the name() and pass() go for the catch(exception e) block. When I run this code, the output from the above try is
Here is the main problem java.util.NoSuchElementException: No line found
The second class
package com.admin;
import java.util.ArrayList;
class Adminstoreroom {
//These arrays are used for Storing accountant info in the admin sections
private static ArrayList<String> accName = new ArrayList<String>(30);
private static ArrayList<String> accPassword = new ArrayList<String>(30);
//Accountant Names
public void setAccName(String an) {
accName.add(an);
}
public String getAccName(int i) {
return accName.get(i);
}
//Accountant Password
public void setAccPassword(String ap) {
accPassword.add(ap);
}
public String getAccPassword(int i) {
return accPassword.get(i);
}

Custom Exceptions String Array

I'm building a custom exception which basically is thrown if an array doesn't contain 5 strings. This is what I have so far. The only exception that really matters is the custom one as I just have to show that that exception is thrown if the array doesn't contain the 5 strings after the input file was split. Any help would be appreciated. Thanks!
package exceptions;
import java.io.File;
import java.util.Scanner;
public class Exceptions {
public static void main(String[] args) {
String input, formattedInt, field[];
int recordNumber = 0;
int length;
Scanner inputFile;
try {
inputFile = new Scanner(new File("data.txt"));
while (inputFile.hasNextLine()) {
recordNumber++;
formattedInt = String.format("%2d", recordNumber);
input = inputFile.nextLine();
field = input.split(",");
length = field.length;
if (field.length != 5) throw new CustomException(field.length);
System.out.println("Record #" + formattedInt + ": " + input);
}
} catch (Exception e) {
System.out.println("Error! Problem opening file.\nError was: " + e);
} catch (CustomException ce) {
System.out.println(ce);
}
}
}
CustomException.java
package exceptions;
public class CustomException extends Exception {
private int fieldcount;
public CustomException(int fieldCount) {
super("Invalid Count: " + fieldCount);
}
public int getCount() {
return fieldcount;
}
}
CustomException extends Exception so any CustomException will be caught in the first catch block.
Rearrange your blocks so the catch(CustomException e) block comes before the catch(Exception e) block

Have to enter something twice in scanner when using thread - Java

For some reason, I have to enter something twice for it to print out in Java when Using Scanner in a thread. I dont know why this is, but IT is very annoying. Because of this, My message sends through the socket and gets to the other person but does not show it to the person sending it, but on the second try it shows to the person who sent it but it doesnt get to the person that should receive it!
(If something doesnt look like its from the Java API, its because its a Test Class for My API)
Note: The code is the exact same on both sides, except they use different ports.
private static UDPSocket TestUDP;
private static String Username = "9843";
public static void main(String[] args) {
try {
TestUDP = new UDPSocket(9844);
TestUDP.defineDefaultAddress("localhost", 9843);
Username = "Lawton";
System.out.println("You set your name to: " + Username);
new Thread(new Receive()).start();
new Thread(new Send()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
static class Send implements Runnable {
public void run() {
try {
while (true) {
Scanner UserInput = new Scanner(System.in);
TestUDP.send("0x00", Username + ": " + UserInput.nextLine());
System.out.println(Username + ": " + UserInput.nextLine());
Thread.sleep(1);
}
} catch (Exception E) {
System.err.println("There was a error.");
}
}
}
static class Receive implements Runnable {
public void run() {
try {
while (true) {
byte[] Message = TestUDP.receive();
System.out.println(Packet.decrypt(Message));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use a variable to avoid calling scanner.nextLine() twice:
Scanner UserInput = new Scanner(System.in);
String readUsername = UserInput.nextLine();
TestUDP.send("0x00", Username + ": " + readUsername);
System.out.println(Username + ": " + readUsername);

multithreaded server, loop is working only once

I have problem with my multhreaded server for bridge auction. The topic of it is less important, all I need to do so far is to make the loop inside the run method work for more than only one "lap". I mean my loop is working for each client only once and then It stopped, but I can't solve this problem. It should work all the time and after sequence of players N-> E-> S-> W-> it start another lap from player N, but now it just stand still...
Check my code:
package serwer;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
public class Serwer {
public static void main(String[] args) throws Exception {
System.out.println("Started server to the bridge auction");
int conCount = 0;
ServerSocket serwer = new ServerSocket(9898);
ArrayList<connection> connections = new ArrayList<connection>(){};
try {
//only 4 players are allowed to play bridge in one table
while (connections.size() < 4) {
connection p = new connection(serwer.accept(), conCount++);
connections.add(p);
connections.get(conCount-1).start();
}
} finally {
serwer.close();
}
}
/**
* static class responsible for the connection in multithreaded server
*/
static class connection extends Thread {
private Socket socket;
private int conCount;
private static int counter = 0;
private final String[] Players;
private String stringOnServer = "0";
private int stake = 1;
public connection(Socket socket, int conCount) {
this.Players = new String[]{"N", "E", "S", "W"};
this.socket = socket;
this.conCount = conCount;
System.out.println("New connection id: " + Players[conCount]);
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//here is info what player are you
out.println("You are player on position " + Players[conCount]);
while (true) {
synchronized (this) {
if (counter % 4 == conCount) {
while (true) {
out.println("Your turn " + Players[conCount] + ", please input the text: ");
String input = in.readLine();
System.out.println("\t" + Players[conCount] + " : " + input);
counter += 1;
//for now only the stringOnServer is simply echo
stringOnServer = input;
System.out.println("\tCurrent string on server = " + stringOnServer);
try {
this.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Serwer.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
} else {
this.notify();
}
}
}
} catch (IOException e) {
System.out.println("error with player: " + Players[conCount] + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println("can't closed");
}
System.out.println("connection with player" + Players[conCount] + " terminated");
}
}
}
}
Client's code is really simple, but if someone will have time and patience to test it I add it to:
package klient;
import java.net.*;
import java.io.*;
public class Klient {
public static void main(String[] args) throws IOException {
try {
Socket s = new Socket("127.0.0.1", 9898);
String answer;
System.out.println("Welcome on the server of auction.");
//Here is displayed info from server what player are you
BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(fromServer.readLine());
while (true) {
System.out.println(fromServer.readLine());
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
answer = input.readLine();
out.println(answer);
}
} catch (ConnectException ex) {
System.out.println("There are 4 players on server or server is closed, try again later");
}
}
}
The problem is in this loop in connection class with counter.
Thanks in advance for your help :)
You have to call notify() from another thread. Your current thread is waiting and cannot notify itself.

Categories

Resources