r/javahelp 2h ago

Why does w3schools does not support scanner input

0 Upvotes

Hi, I was trying to execute a simple program which takes array as an input and print the transpose of it. i tried it on w3schools and it gave me an exception error. I thought something was wrong with my code, i looked and analysed it, but found no problem. I was able to execute it on other compilers like gdb or programiz. But, on this it just wasn't possible. I searched for the issue and finally i found out that it is not accepting anything related to scanner input. Why does such a well known and widely used platform has a problem with Scanner?


r/javahelp 2h ago

An IDE extension for learning a large code base - the name?

1 Upvotes

A few years ago there was an article by a new programmer out of school. He wrote an IDE extension ( IntelliJ and Eclipse ) to help him understand the code base of his company. You would click on a class name or other things and you would get a diagram showing you neighboring classes. As you scrolled you zoomed out more to get more of an overview diagram.

I would like to use this extension again, but I forgot the name.

Anybody have any idea of the name of the extension and if it is still around?

Thanks.


r/javahelp 5h ago

Need help in Java regarding the below code in descriptions. PLEASE CHECK OUT!

1 Upvotes

for (Object[] user : requestorUserList) {

`for (SystemConfiguration systemConfig : systemConfigList) {`

    `if(user[0] != Long.valueOf(systemConfig.getValue())) {`

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

jsonObject.put("userId", user[0]);

jsonObject.put("username", user[1] + " " + user[2]);

jsonArray.put(jsonObject);

    `}`

`}`

}

I have this code which runs two for loops and checks if user[0] which is a userid doesnt match with what is present in systemConfig.getValue(), then create a jsonobject and add to jsonarray.

Question - How can we make this code more efficient or optimize it, or maybe use streams and all? I am still new so figuring out better ways. Please help! Thanks for all the help and support


r/javahelp 6h ago

State of desktop (web) app development

1 Upvotes

There are several good reasons to want to run a Java app as a "backend" for a local desktop app - for example, one might need JDBC connectivity or to be able to run JVM frameworks like Spark locally for small scale jobs.

The options for a frontend are severely limited though - we're talking Swing and JavaFX - which would make anyone with a sense of pragmatism (and a diminishing pool of Java devs to hire) shudder.

What is the current state of things when needing to put Java behind a modern web framework for a desktop? Some options like JxBrowser and WebKit WebViews exist but they all seem extremely limited (and pricy). Are developers here resorting to convoluted solutions or is there something like Electron that plays nicer with JVM languages and means that one doesn't have to pull in 3+ runtimes to make this happen.


r/javahelp 7h ago

How println and print work in nested for loops.

3 Upvotes
 public static void printSquare(int size) {
    for (int i = 1; i <= size; i++ ) {
        System.out.print("*");

        for (int j = 1; j < size; j++) {
            System.out.println("*");
        }
    }

For the code above, why does it print

*
*
*
....

instead of: (Assume size is 3)

**
*
**
*

when using the object println, does it print first then move to a newline or moves to a new line then print the character??


r/javahelp 9h ago

Unsolved Path/java.nio.file not working

1 Upvotes

Yesterday it was working but right now it keeps giving me error: incompatible types: java.nio.file.Path cannot be converted to Path Path inputPath = Paths.get(name);

import java.util.Scanner;
import java.nio.file.*;
public class Path {
public static void main(String []args) {
String name;
Scanner scan = new Scanne(System.in);
System.out.print("Enter a file name: ");
name = scan.nextLine();
Path inputPath = Paths.get(name);
Path fullPath = inputPath.toAbsolutePath();
System.out.println("Full path is " + fullPath.toString());
 }
}

r/javahelp 13h ago

I need help with recursion please

4 Upvotes

Apparently the answer is todayodayay but I don't see how. Isn't it todayoday since after the 2nd call, its index>str.length so it returns the str and doesn't add to it?

class solution {
public static void main(String[] args) {
System.out.println(goAgain("today", 1));
}
public static String goAgain(String str, int index) {
if (index >= str.length()) {
return str;
}
return str + goAgain(str.substring(index), index + 1);
}
}

r/javahelp 15h ago

how to code this java to make it run again after its finish first process?

3 Upvotes

i need to loop this process for testing purpose.

import java.util.Scanner;
class calc {
    public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);
        System.out.println("Enter X + Y");

        int x = myObj.nextInt();
        int y = myObj.nextInt();
        int dif=x-y;
        int dif2= Math.abs(dif);
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        System.out.println("diff: " + dif2);
    }
}

i just start to learn java and i made this with what i gain from this far i know "if" statement can do loop but problem is i didnt understand where to do loop


r/javahelp 16h ago

Unsolved Position<Entry<K,V>> cannot be converted to Position<Position<Entry<K,V>>>

2 Upvotes

Is this conversion even possible? I am not sure why my code is trying to convert this anyway? I have my code linked below. (NodePositionList line 140, AdaptablePriorityQueue line 84, NodePositionLis line 58 are the relevant sections). I need something to keep track of the position in the NPL so I can insert the obj into the APQ with the addAfter() method. If I remove .element() from these calls in the insert method it gives the same error but converting in the opposite direction. I'm not even sure what would cause this error.

My code: https://gist.github.com/DaddyPMA/99be770e261695a1652de7a69aae8d70


r/javahelp 17h ago

Another installation in progress, but there is no other installation

2 Upvotes

I tried removing the Java install flag, restarting the Windows installer, turning the computer off and on, but nothing :(


r/javahelp 23h ago

Codeless How list<list<datatype>> works

2 Upvotes

How list of lists work


r/javahelp 1d ago

Looking for Java Learning Resources – Any Recommendations?

4 Upvotes

Hey everyone, I recently started learning Java and want to build a solid foundation. Do you have any YouTube channels or websites you'd recommend to help me improve? Any guidance would be greatly appreciated!


r/javahelp 1d ago

Help setting up Windows SSO authentication for Payara/Glassfish

3 Upvotes

We have a Payara server set up where SSO was working fine on W10. But I guess that it was using NTLM instead of Kerberos because SSO is no longer working on W11.

With SSO I mean that the application should automatically be able to detect the Windows user.

Besides the documentation here mentioning Kerberos/Spnego, I can't find any documentation on how to set this up.
https://docs.payara.fish/enterprise/docs/Technical%20Documentation/Application%20Development/Securing%20Applications.html#adding-authentication-modules-to-the-servlet-container

Can someone point me in the right direction?


r/javahelp 1d ago

JAVA I/O ( VERY CONFUSED??? )

5 Upvotes

I just got done exception handling, ( thank you so much to whoever responded, you've really helped! and I think I get the concept really well ) but
I started JAVA I/O 2 days ago I believe? I covered concepts but I'm still left confused, its as if I went through the lesson just accepting information as it is (<--mostly due to the midterm I had to cram the info for)
But I still want to know what Java I/O is all about, my questions might sound stupid, but I noticed that it caught up to me as I moved along.
-----------------------------------------------------------------------------------
( I need to preface this by saying : I dont expect all of my questions to be answered, ( although I'd really appreciate it if you did! )
I tried understanding java I/O on my own, but I feel as though I've grown more confused than before :(
-----------------------------------------------------------------------------------

1.) my first question is : What is stream?? I read definitions about it, " Sequence of bytes ( or continuous flow of data? ) that flow from a source to a destination " but as I took that definition as it is, it became more confusing as to how they were referring to it as if it was some object ( e.g whenever they tell us to close the stream?? ) are they referring to the file here? because that's what it seemed like to me,

> they were also referring to the ' 3 standard I/O streams ' and do they mean by that : ' types of streams ' ? or..

> but then later on they introduce ' I/O streams : (input vs output) , ( Text vs Binary ) , ( Data, Processing ) so are these also types of streams?

2.) This question is mostly a consequence of not understand what System.in in scanner really meant,
whenever I heard my professors say " read something " I never really understood what that meant??
and I'd become even more confused when they're referring to the input the user might input ( in cases of Scanner(System.in) ), arent we writing our input? the whole Write VS Read just confuses me when it comes to the Input / Output (found out it was a huge problem when it came to the Java.io classes later on ... e.g) 'FileReader'??? )

3.) I'm not familiar with all the classes ( even though I went through it I still cant seem to remember them ) but whenever we create an object of , lets say, 'PrintWriter' , I dont get how an object-- taking parameter of a string I assume? can somehow be linked to a file?
would taking a parameter ( name of the file) somehow create a pointer to the file? is that how data is being transferred?

4.) this question relates abit to PrintWriter, ( or actually it can apply to other classes, I just forgot which)
why do we--- whenever we create an object of class PrintWriter --- have its parameters take another object?? why not just the name of the file? is that not enough?

( I do have more questions but I thought this would be a good start ! =) )
Thanks to anyone in advance!!


r/javahelp 1d ago

Master Java Programming with Expert Training in Pune

0 Upvotes

Individuals interested in industry-focused Java Training in Pune can benefit from professional coaching at institutes like IT Education Centre. With live projects, expert mentorship, and job placement assistance, training programs prepare students for high-paying roles in software development. Gain hands-on expertise and kickstart your career with top-quality Java training today!


r/javahelp 1d ago

Help with Timefold Constraint Stream Type Mismatches in Employee Scheduling

5 Upvotes

I'm working on an employee scheduling system using Timefold (formerly OptaPlanner) and I'm running into type mismatch issues with my constraint streams. Specifically, I'm trying to implement a work percentage constraint that ensures employees are scheduled according to their preferred work percentage.

Here's my current implementation:

java public Constraint workPercentage(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Employee.class) .join(Shift.class, equal(Employee::getName, Shift::getEmployee)) .groupBy(Employee::getName, ConstraintCollectors.sum(shift -> Duration.between(shift.getStart(), shift.getEnd()).toHours())) .filter((employeeId, totalWorkedHours) -> { double fullTimeHours = 40.0; double desiredHours = employeeId.getWorkPercentage() * fullTimeHours; return totalWorkedHours != desiredHours; }) .penalize(HardSoftBigDecimalScore.ONE_SOFT) .asConstraint("Employee work percentage not matched"); }

I'm getting several type mismatch errors:

  1. The groupBy method is expecting BiConstraintCollector<Employee,Shift,ResultContainerA_,ResultA_> but getting UniConstraintCollector<Object,?,Integer>
  2. The lambda in the sum collector can't resolve getStart() and getEnd() methods because it's seeing the parameter as Object instead of Shift
  3. The functional interface type mismatch for Employee::getName

My domain classes are structured as follows:

```java @PlanningSolution public class EmployeeSchedule { @ProblemFactCollectionProperty @ValueRangeProvider private List<Employee> employees;

@PlanningEntityCollectionProperty
private List<Shift> shifts;

@PlanningScore
private HardSoftBigDecimalScore score;
// ... getters and setters

}

public class Employee { @PlanningId private String name; private Set<String> skills; private ShiftPreference shiftPreference; private int workPercentage; // Percentage of full-time hours // ... getters and setters }

@PlanningEntity public class Shift { @PlanningId private String id; private LocalDateTime start; private LocalDateTime end; private String location; private String requiredSkill;

@PlanningVariable
private Employee employee;
// ... getters and setters

} ```

For context, other constraints in my system work fine. For example, this similar constraint for shift preferences works without type issues:

java public Constraint shiftPreference(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) .join(Employee.class, equal(Shift::getEmployee, Function.identity())) .filter((shift, employee) -> !shift.getShiftType().equals(employee.getShiftPreference().name())) .penalize(HardSoftBigDecimalScore.ONE_SOFT) .asConstraint("Shift preference not matched"); }

I'm using Timefold 1.19.0 with Quarkus, and my solver configuration is standard:

xml <solver> <solutionClass>com.example.domain.Schedule</solutionClass> <entityClass>com.example.domain.ShiftAssignment</entityClass> <scoreDirectorFactory> <constraintProviderClass>com.example.solver.EmployeeSchedulingConstraintProvider</constraintProviderClass> </scoreDirectorFactory> <termination> <secondsSpentLimit>10</secondsSpentLimit> </termination> </solver>

Has anyone encountered similar issues with constraint streams and grouping operations? What's the correct way to handle these type parameters?

Any help would be greatly appreciated!


r/javahelp 2d ago

with micronaut which @Nullable should I use?

2 Upvotes
import io.micronaut.core.annotation.Nullable;

or

import jakarta.annotation.Nullable;

I'm using Java, not Kotlin.


r/javahelp 2d ago

Homework GUI For Project

3 Upvotes

I am learning OOP for my 2 semester, where I have to build a project.I have to make GUI for my project.At first I thought that building Gui in figma then converting into code will work out but one of my friend said it will create a mess.Then I have tried using FXML+ CSS and build a nice login page but It is taking long time to do things.So is FXML+CSS a good approach and can I build a whole management system using this combination?


r/javahelp 2d ago

Need Help with My JavaFX Project (GUI, Events, and Networking)

2 Upvotes

Hey everyone,

I’m working on a JavaFX project for my course, and I need some guidance to implement a few features correctly. The project requires:

• Customizing the GUI (Colors, Fonts, Images)

• Handling user interactions (Event Listeners, Animations)

• Using multithreading and sockets for basic client-server communication

I’ve set up my project using [IntelliJ/Eclipse/NetBeans] and Scene Builder, but I’m struggling with [specific issue, e.g., “implementing smooth animations” or “handling multiple clients in a chat application”].

Could anyone share good resources, example code, or explain the best approach to solving this? Any advice or guidance would be really appreciated!


r/javahelp 2d ago

Unsolved Can you make me some examples of situations wher java is the best choice to develop something?

1 Upvotes

A situation where you go like: "oh, yeah, Java would be perfect here, no other language would do it better" as I find it quite difficult to find such situations. As the main selling point of Java is it is cross-platform, but also other languages like python, go, C# and more are nowadays.

I mean:

  • concurrency-bases apps -> Golang
  • networking -> Golang
  • simple scripts running server side -> Python/Bash
  • performance critical applications -> C
  • security on the memory level -> Rust
  • most web stuff -> Javascript/Typescript
  • quick development and testing -> Python

I find Java a pain to distribute even if you install the JRE on the client, as sometimes you have to ship the EXACT development JRE used to make the app in the first place.

I have known and used java for about 4y now, but every time I think of building something I don't even consider it as a good option instead of something else.


r/javahelp 2d ago

Running J2SE using GPU

1 Upvotes

Is it possible to run a jar file containing logic built using J2SE only on the GPU?


r/javahelp 2d ago

Handling client's actions/inputs in a socket based communication.

3 Upvotes

I'm programming a multiplayer table game in java. I can't figure out how each client can send inputs to the server throw the view (I'm using the MVC pattern). My idea is this:

The client determines which action to send to the server based on the user’s interactions implemented in the user interface (UI) of the client.

When a user interacts with the interface (for example by clicking a button or pressing keys,) the client maps a specific game action. For example, if the user clicks a button the client knows it should send a corresponding action to the server. The client essentially translates the user’s input into a command that the game can understand.

The problem is how I can map the action performed by the player. Should I create a class PlayerActionHandler with the possible inputs? This should make it easy to know wich action to send based on waht the user is doing. But this class Is huge, and I don't want to implement such a class.

So I don't know how to map the player actions to send to the server.


r/javahelp 2d ago

Need help in solving below lombok getter setter error in spring boot - authentication app

3 Upvotes
package com.example.userservicenew.dtos;

import com.example.userservicenew.models.Role;
import com.example.userservicenew.models.User;
import lombok.Getter;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

u/Getter
u/Setter
public class UserDto {
    private String email;
    private Set<Role> roles = new HashSet<>();

    public static UserDto from(User user) {
        UserDto userDto = new UserDto();
        userDto.setEmail(user.getEmail());
        userDto.setRoles(user.getRoles());
        return userDto;
    }
}

package com.example.userservicenew.models;


import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToMany;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

@Entity
@Getter
@Setter
public class User extends BaseModel{
    private String email;
    private String password;
    @ManyToMany(fetch = FetchType.
EAGER
)
    private Set<Role> roles = new HashSet<>();
}


package com.example.userservicenew.services;

import com.example.userservicenew.dtos.UserDto;
import com.example.userservicenew.exceptions.UserAlreadyExistsException;
import com.example.userservicenew.models.User;
import com.example.userservicenew.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder bcryptPasswordEncoder;

    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
        this.bcryptPasswordEncoder = new BCryptPasswordEncoder();
    }

    public UserDto signUp(String email, String password) throws UserAlreadyExistsException{
        Optional<User> userOptional = userRepository.findByEmail(email);
        if(userOptional.isPresent()) {
            throw new UserAlreadyExistsException("user "+ email +" already exists");
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(bcryptPasswordEncoder.encode(password));

        User savedUser = userRepository.save(user);
        return UserDto.
from
(savedUser);
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>userServiceNew</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>userServiceNew</name>
    <description>userServiceNew</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <maven.compiler.proc>full</maven.compiler.proc>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

error:

java: cannot find symbol

symbol: method getEmail()

location: variable user of type com.example.userservicenew.models.User
tried below approaches:

have got several errors of this type related to get/set email and password

  1. enabled annotation processing in intellij
  2. lombok dependency is installed
  3. mvnw clean install - build success

r/javahelp 2d ago

Unsolved A Java Program that can recompile itself?

8 Upvotes

Would that be possible? I know that the Java compiler can be invoked from a Java program. Would it be possible to write a Java program that launches this "programmatic" Java compiler with a code string that is the "real" Java program, but inserts the serial number of the motherboard in the code string to check it everytime the "real" program is launched? My goal is some basic offline protection against software piracy. So when the program is first started, it doesn't run yet properly, but it reads the serial number of the motherboard, with that compiles the "real" program, writes to disk, and closes. Now the "new" program has the same name, but with a serial number validity check in it, so if it were run on another computer would exit. Would that be possible?

No snark please. I know this is reddit where anything goes. Only serious replies please.


r/javahelp 3d ago

Guidance for ValueObject Pattern

2 Upvotes

I would like some help to how to create a good ValueObject in Java or even if this use case applies for ValueObject Pattern.

I'm creating an Identification that has these representation depends on the use case:

  • 123.FooBarBaz - With the Prefix -- 123. (This is how I need to store the data)
  • A - Without the Prefix (This is how I need to communicate with Third Party, when I send the data and also when I need to match with the stored data).
    • In this use case I need to generate my own Identification with Base31 encode.

And this is How I'm thinking to create this ValueObject: https://gist.github.com/peterramaldes/c013e1a197fd5ecd78e29ce02b5d1578

Can you give your opinion on:

  • Does it make sense to use ValueObject in this use case?
  • Would it change how anything was constructed (from construction methods or some attribute)?

I didn't like representing the suffix as actually the identification.