r/javahelp • • Jun 17 '19

Getting a countdown timer to display minutes:seconds

0 Upvotes

Hey all

Let me preface this by saying that I am an extreme beginner. I have never even viewed html markdown until a couple of coding sessions ago... much less used java. However i'm required to use both to display an experiment I am running via a website. It's extremely 90's looking but everything is pretty much done/bearable except this timer.

On certain pages I require a countdown timer to start on page open. at the end of the time limit a buzzer should sound, and the participant should be directed to the next page in the sequence. Good news is: I actually have got that working myself! (this is pathetic but i fell like a wizard right now xD). Got the timer from here, inserted my own locally hosted link, and added a new if clause for audio.play for a locally hosted sound.

The remaining problem is this: ideally i'd like to display the countdown in a minutes:seconds format. For example 1:35 instead of 95 seconds. Here's my current code for the timer (in case it is relevant its sitting in the nav bar of the html markdown):

<h3>Time Remaining: <span id="countdown">120</span> seconds</h3>

<!-- JavaScript part -->

<script type="text/javascript">

// Set Time limit

var seconds = 120;

// Define time-end buzzer

var buzzer = new Audio('buzzer.wav')

// Define count process

function countdown() {

seconds = seconds - 1;

if (seconds == 1) {

// Play buzzer

buzzer.play();

}

if (seconds < 0) {

// Direct to next page

window.location = "Task_A_3_Splash.html";

} else {

// Update remaining seconds

document.getElementById("countdown").innerHTML = seconds;

// Count down using javascript

window.setTimeout("countdown()", 1000);

}

}

// Run countdown function

countdown();

</script>

I've tried using 'var minutes = 2' to set my time limit, on the off chance that Java would "know" what a minute is. Of-course that didn't work - and i suspect the idea is dumb one. My best guess would be that I have to somehow define what one minute is as var minutes = seconds*60, and then somehow have the countdown juggle both variables... or... something? That may also be a dumb idea.

I'd like to be able to evidence more thing's i've tried as per the guidelines... but the truth of the matter is i've gone from nothing to a (crap) website with this code in it in a couple of afternoons and i've plain reached a point where I just don't know how to progress. Not necessarily looking for a finished solution, but if someone could even point me in the right direction (maybe commands, or similar examples...) that'd be such a big help!


r/javahelp • • Jul 24 '20

Codeless New Java Features implemented by me

0 Upvotes

I saw a lot of people asking for a lot of features, so I thought, why not implement them? So I created a new project and I added some features a lot of you asked for. I implemented uint, BetterLists (I will talk about them later in this post) and a Testing class.

Basically the better lists are lists that have more methods. They can be reversed and some more features I forgot I added. BUT I added the feature that I saw everyone wanted. When you use the getValue(int index) method, you can pass a negative number. If the number you passed is negative, the list will take it from the end to the beginning. Check below.

BetterList<String> test = new BetterList<String>("1", "2", "3"); test.getValue(2); //will return "3" test.getValue(-2); //will return "2"

So this is what I created. I will give the code soon. Anybody who is interested or wants more features?


r/javahelp • • Jul 25 '20

Can you review my code?

0 Upvotes

I recently created a program that could get information from a client, a name and some text, and then put that into a text file. From there the user can get open the text file straight from the program. I made it in two days. Please give me some tips in ways I can improve it, thank you!

The Server:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class Server {
static boolean isAvailable = false;

public static void main(String[] args) throws IOException {

    // Get both connections to the client
    ServerSocket serverSocket =
            new ServerSocket(4999);
    ServerSocket serverSocket2 =
            new ServerSocket(4998);
    Socket socket =
            serverSocket.accept();
    Socket socket2 =
            serverSocket2.accept();

    // Confirm client connection
    System.out.println("The client has been connected to the server");

    // Get the streams from the client containing the string
    InputStreamReader fileNameIn =
            new InputStreamReader(socket.getInputStream());
    BufferedReader br =
            new BufferedReader(fileNameIn);

    InputStreamReader informationIn =
            new InputStreamReader(socket2.getInputStream());
    BufferedReader br2 =
            new BufferedReader(informationIn);

    // Read and assign the strings
    String fileName =
            br.readLine();
    String fileInformation =
            br2.readLine();

    // Get char array to write to the created file
    char[] fileInformationC =
            fileInformation.toCharArray();

    // Create file and write to it
    try (FileChannel fileChannel =
                 (FileChannel) Files.newByteChannel(
                         Path.of("C:\\Users\\Emman\\" + fileName + ".txt"),
                         StandardOpenOption.CREATE,
                         StandardOpenOption.WRITE
                 )) {

        int allocatedVal = 1000;

        ByteBuffer byteBuffer =
                ByteBuffer.allocate(allocatedVal);


        for (char c : fileInformationC){
            byteBuffer.put((byte) c);

            // Error handling: it is now impossible for the Buffer to run out of space
            // However a BufferOverflowException is caught, in case of a problem
            if (!(byteBuffer.position() == allocatedVal)){
                ByteBuffer.allocate(allocatedVal * 2);
            }
        }

        byteBuffer.rewind();

        fileChannel.write(byteBuffer);

        System.out.println("File has been created and written to, \n" +
                "Press Enter to open file");

        // The input does not matter
        //noinspection ResultOfMethodCallIgnored
        System.in.read();
        ProcessBuilder processBuilder =
                new ProcessBuilder("notepad.exe", "C:\\Users\\Emman\\" + fileName + ".txt");
        processBuilder.start();
    } catch (InvalidPathException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("\"Error in creating/writing to file \\n\" +\n" +
                "Due to incorrect/invalid path\" +\n" +
                "e");
        printToClient.close();
    } catch (IOException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("Error in creating/writing to file \n" +
                "Due to error in IO" +
                e);
        printToClient.close();

    } catch (BufferOverflowException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("Error in creating/writing to file \n" +
                "Due to a buffer overflow" +
                e);
        printToClient.close();
    }

}
}

The Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
public static void main(String[] args) throws IOException{

    // Create connections to server
    Socket socket =
            new Socket("localhost", 4999);
    Socket socket2 =
            new Socket("localhost", 4998);
    // Create print writer output stream to give to server
    PrintWriter pr =
            new PrintWriter(socket.getOutputStream());
    PrintWriter pr2 =
            new PrintWriter(socket2.getOutputStream());

    // Create a buffered reader for reading the file name and information
    BufferedReader br =
            new BufferedReader(
                    new InputStreamReader(
                            System.in
                    )
            );

    // Get the file names and information
    String fileName = br.readLine();

    String information = br.readLine();

    // Put in the file Name and the file information
    pr.write(fileName);
    pr.close();

    pr2.write(information);
    pr2.close();

    // Checking whether the error message is available,
    // if not only one line of code is read, wasting barely any time
    if(Server.isAvailable){
        InputStreamReader errorInfoIn =
                new InputStreamReader(socket.getInputStream());
        BufferedReader readErrorInfo =
                new BufferedReader(errorInfoIn);

        String errorInfo =
                readErrorInfo.readLine();
        System.out.println(errorInfo);
        errorInfoIn.close();
    }
}
}

r/javahelp • • Jul 22 '20

"Pointer" in java?

0 Upvotes

Was learning Recursion from GeeksforGeeks, when I came across this code snippet -

static void abc(char *s) 
{ 
    if(s[0] == '\0') 
        return; 
    
    abc(s + 1); 
    abc(s + 1); 
    System.out.print(s[0]);     
} 

In Java, we have “references”, and not an actual “Pointer” type, by which we can go in to a memory address in the JVM directly. So, what is a char pointer doing in Java? Unless my whole life has been a lie?

Problem link - https://www.geeksforgeeks.org/practice-questions-for-recursion-set-6/.


r/javahelp • • Jul 22 '20

Hey Team, I just created a COVID 19 tracker for India, I am thinking about expanding it to provide the stats of the whole world, if anyone wants to collaborate with me, please join, it will be a fun little project.

0 Upvotes

r/javahelp • • Aug 10 '20

Is it possible to print two different receipts to two separate printers?

0 Upvotes

I couldn’t find any information on it. For example, one receipt for the customer, very detailed, whole a different one for the kitchen that can be very basic


r/javahelp • • Jul 28 '20

Warning when accessing static variable from a different class

0 Upvotes

Hello, I am doing a project where a class variable gets updated and that new value needs to go into a different class. The only way i was able to do this was by making it a static variable in its original class and then referencing it by className.staticVariable , but this gives me warnings in the IDE despite it working fine. I was wondering if theres a way to accomplish the same thing but without getting the warning, or if it is fine as it is. The warning reads : The static field className.staticVariable should be accessed in a static way. I have tried getting it to work by using object of the classes involved but these attempts just gave me overflow errors. Any help would be appreciated


r/javahelp • • May 14 '20

Return html template with data from java

0 Upvotes

Hi, I'm looking for a way to return a html template from java where I can insert data I have in Java. I think the replace part in html wouldn't be a problem using jquery, but I need a way to give the data I have in java into the html template..

So let's say my html file looks like this:

<html>
  <body>
    <h1>Some header</h1> 
    <p>Here is where the Data is supposed to go</p>
  </body>
</html>

Now I need a String variable at <p>

so

String content = "Hello World";

In the end the returned file should look like that:

<html>
  <body>
    <h1>Some header</h1> 
    <p>Hello World</p>
  </body>
</html>

Sounds pretty easy, but how do I pass the String into the template File? Is there some kind of technology?

Thanks.

Best I found now is this. Gonna go for this for now. If anyone has a cleaner solution please feel free to comment.


r/javahelp • • Apr 20 '20

Inheritance question

0 Upvotes

This is the code the professor gave us and I have no idea what to do with it. He wants me to print out i and j. I've tired changing a few things but I don't understand the code in general and I am always getting an error in class inherited. I tried changing "class B extends A" to "class B extends Inheritance" and this gets rid of that error but at the "System.out.println(obj.i + " " + obj.j);" there's always an error with i&i that states they cant find them. I named the super class Inheritance and the subclass inherited btw. Thank you ahead of time for any help.

class A

{

public int i;

public int j;

A()

{

i = 1;

j = 2;

}

}

class B extends A

{

int a;

B()

{

super();

}

}

class super_use

{

public static void main(String args[])

{

B obj = new B();

System.out.println(obj.i + " " + obj.j);

}

}


r/javahelp • • May 11 '20

why cant i access this object?

0 Upvotes

https://imgur.com/a/hSrKv25

so it says it cant make a static refference to a non static field. but from what i understand, its not static. i created an object called test1 if the class test and want to access the method toString from that object. but i cant. why? i looked through my other programs and its exactly the way i always did it. what did i do wrong?


r/javahelp • • Apr 02 '20

Homework I'm losing my mind

0 Upvotes

I'm having so mutch trouble handle with the input the assignment is : "Design the program" NameShuffler" that: ask to use up to 10 full names up to 120 characters and that each one contains at least two names with less than 4 characters; ending when it has reached the limit or when the user will use the "end" (it is not case sensitive) as a name and there are already 5 valid names. Each invalid name must be discarded, the user being notified of this fact. No final name entry should show a listing of the data entered; after obtaining the first and last name of each name, which contains 4 or more characters; generate as many new names as the ones that were introduced with a first name and a last name, already selected, chosen at random but without repetitions (no more repetitions than there is already by introducing repeated names); and show the new names on the console. To process each name, use a Scanner and String class to use the length () method."


r/javahelp • • Nov 11 '18

I've my Variables changed and i cant Solve it

0 Upvotes

Im new in this platform, greetz for the site. Now

This is the proyect https://github.com/anb00/BossBeta.git

For example when im trying to Map @RequestMapping("/getProductById/{id} i cant get the correct info

for a list of details i have the classes done and some lists in other clases but doesnt work.

The MyController is the Main file and for Run it is the RunSpringApp or Application both works.


r/javahelp • • Mar 12 '20

While loop keeps looping even when condition is met

0 Upvotes

This is the code:

package FirstPackage;

import java.util.Scanner;

public class TheLastHero {

public static void main(String[] args) {

System.out.println("Welcome you are the last Hero please save the land from the monsters that are plaguing it by killing the boss in the dungeon Type \\"Start\\" to Begin");

Scanner Inp = new Scanner([System.in](https://System.in));

String Val = (Inp.nextLine()).toUpperCase();

while (Val != "START"){

	System.out.println("Please enter \\"Start\\" to begin");

	Val=(Inp.nextLine()).toUpperCase();

	System.out.println(Val);

}

}

}

And this is the result:

Welcome you are the last Hero please save the land from the monsters that are plaguing it by killing the boss in the dungeon Type "Start" to Begin

dsd

Please enter "Start" to begin

Start

START

Please enter "Start" to begin

As you can see even when the condition is met it keeps looping

Edit : Sorry apparently it s a stupid question i just needed to use !.equals instead of !=


r/javahelp • • Feb 16 '22

Java Application Project

0 Upvotes

Hello,

Any ideas for a simple Java Application development project please???


r/javahelp • • Feb 19 '22

Need help

0 Upvotes

Does anybody have any idea on how I should do this I made an ArrayList that will hold newMembers I want to update the list with the users input.

But I want to update 3 parameters at a time the name the monthly payment and the paymentMethod how should I do this


r/javahelp • • Jan 26 '22

UserClass existingUser = new UserClass("", "", "", "", "", ""); but with integer?

0 Upvotes

I'm trying to create a new UserClass but it contains userID which is an integer, what should I replace the " " with?


r/javahelp • • May 12 '19

I can't execute java code after compiling

0 Upvotes

Hi there
Is there anyone that have come across this error:
Error:Could not find or load main class
Caused by: java.lang.ClassNotFoundException
I deleted and added the classpath reinstalled java but nothing has helped
The code compiles but it doesn't run


r/javahelp • • May 12 '19

Solved Why does x equal 40 after the code executes?

0 Upvotes

int x = 10;

for (int y = 5; y < 20; y +=5)

x += y;


r/javahelp • • Feb 06 '16

Solved How can I write this so that the program prompts user for username and password (both predetermined) and displays a custom exception when the wrong username or password is typed?

0 Upvotes

I have basically written a try block with the prompt and the catch with the exception "Enter correct username or password". Do I have to throw and exception within the try block in an if statement? Here is what I have.

import java.util.*; public class MainDriver {

public static void main(String[] args){

	Scanner input = new Scanner(System.in);
	
	try{
		System.out.print("Enter username: ");
		String username = input.nextLine();
		System.out.print("Enter password: ");
		String password = input.nextLine();
		if(username!="admin" || password!="password"){
			throw new Exception();
		}
	}catch(Exception e){
		System.out.print("Enter correct username and password");
	}
}

}

this just asks the user to enter the username and password no matter what they enter


r/javahelp • • Jun 22 '22

Unsolved How to Fix the Following Error: Cannot invoke “String.length()” because “this.InputStr” is null.

0 Upvotes

Since my professor is no help....... Below is the code. In the Main code, the default is"", and the user can update it. However, I continue to get the error message no matter what I do.

/* Returns the count of vowel A.  */ 
public int getCountA(){
inputStr = inputStr;
for (int i = 0; i < inputStr.length(); i++) {
  if ((inputStr.charAt(i) == 'a') || (inputStr.charAt(i) == 'A')) {    
  vowelCount++;
  }
}
return vowelCount;

}


r/javahelp • • Jul 11 '22

LeetCode 3 sum help!!

0 Upvotes
class Solution {
    
    public List<List<Integer>> threeSum(int[] nums) {
        
        List<List<Integer>> ans = new ArrayList<>();
        
        Set<List<Integer>> fin = new HashSet<>();
        
        for(int i = 0; i < nums.length; i++){
            Map<Integer, Integer> map = new HashMap<>();
            int target = -nums[i];
            
            for(int j = 0; j < nums.length; j++){
                
                if(i == j)
                    continue;
                
                if(map.containsKey(nums[j])){
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[j]);
                    tmp.add(map.get(nums[j]));
                    tmp.add(nums[i]);
                    Collections.sort(tmp);
                    fin.add(tmp);
                }
                else{
                    map.put(target-nums[j], nums[j]);
                }
            }
        } 
        
        //System.out.println(fin);
        Iterator<List<Integer>> itr = fin.iterator();
        while(itr.hasNext()) {
           ans.add(itr.next());
        }
         
        return ans;
        
    }
}

r/javahelp • • Jun 15 '17

What's wrong with my code??

0 Upvotes

Can't for the life of me figure it out. Picture of code and error: http://imgur.com/a/mX9XP

Thanks


r/javahelp • • Jun 18 '17

How do I do if statments with a text field?

0 Upvotes

I want to make a program where if someone enters an certain name in the text field it says Hi, but if you enter not the right name it says something else. I just dont know the code for how do the If statement with a Text Field, Please Help!


r/javahelp • • Jun 11 '17

Print Tic-tac-toe board Error output

0 Upvotes

Objective: Complete the printTicTacToe method with char parameters horizChar and vertChar that prints a tic-tac-toe board with the characters as follows. End with newline. Ex: printTicTacToe('~', '!') prints: x!x!x

x!x!x

x!x!x Hint: To ensure printing of characters, start your print statement as: System.out.println("" + horizChar ...).

My code:import java.util.Scanner;

public class GameBoardPrinter { public static void printTicTacToe(char horizChar, char vertChar) {

for(int i=1;i<4;i++){ for(int j=1;j<4;j++){ System.out.print("x"); if(j<3){ System.out.print(vertChar); } } System.out.print("\n"); if(i!=3){ for(int j=1;j<6;j++){ System.out.print(horizChar); } } } return; }

public static void main (String [] args) { printTicTacToe('~', '!');

  return;

} }

Error Out put: Testing with '~', '!' Whitespace differs; see green (missing whitespace) or red (extra whitespace) boxes below. Expected output: x!x!x ~~~~~ x!x!x ~~~~~ x!x!x Your output: x!x!x

~~~~~x!x!x
 
Where did I go wrong and how do I go about fixing it? 
Thanks in advance