Primality Test for 2^n -2

So the question I have is how do i implement this formula: A positive integer n (larger than 1) is a prime if and only if n divides 2^n-2. So far i came up with this code, but i am stuck. I am a newbie at this, just starting to learn java, any help would be great, thanks!

public boolean isPrime(int x){
     if(x==1) 
        return false; 
     if(x==2) 
        return true;
     if(x % 2 == 0)
        return false;

     for(int i=3; i<Math.sqrt(x); i++)

This is where i am confused.

Exception in thread โ€œmainโ€ java.lang.StringIndexOutOfBoundsException: String index out of range: -18

This is my code

import java.util.Scanner;
import java.io.*;

class Main {
public static void main (String[] args)throws IOException {
  Scanner scan = new Scanner(System.in);
  System.out.println ("Enter message board post:");
  String username = scan.nextLine();
  String check = username.substring (username.indexOf(" ")+3 , username.length()).toLowerCase()+" ";
  int a = check.indexOf(" ^^ ");
  int b = check.indexOf (" qey ");
  int c = check.indexOf (" $ ");
  String first = username.substring (0 , username.indexOf(" "));
  int x = 0;
  int y =0;
  int z = 0;
  while (a != -1) {
    x++;
  check = check.substring(a+1, check.length()); 
  a = check.indexOf(" ^^ "); }
  while (b != -1) {
    y++;
  check = check.substring(b+1, check.length());
  b = check.indexOf(" qey "); }
  while (c != -1) {
    z++;
  check = check.substring(c+1, check.length());
  c = check.indexOf (" $ "); }
  if ( x > 0  || y > 0 || z > 0){
    System.out.println ("");
    System.out.println ("BAD");
      System.out.println (first);
      System.out.println ("^^: " +x);
      System.out.println ("qey: " +y);
      System.out.println ("$: " +z);

  }else {
      System.out.println ("");
      System.out.println ("CLEAN");
    }
  }
}

In the end the result is:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -18
at java.lang.String.substring(String.java:1967)
at Main.main(Main.java:23)

Which parts do I have to change to get rid of the thread?
I input B0rg – resistance is futile QeY hahahaha $$$ ^^

and it should show up as

BAD
B0rg
^^: 1

qey: 1
$: 0

But it showed up as exception… Please help me…

AI Chess Java Misunderstanding?

My Professor gave us a template code in Java to make a white pawn move. I have no idea what the code means.

I don’t know if I can post all of it, so I will post a snippet.

    if(pieceName.equals("WhitePawn")){
        if(startY == 1)
        {
            if((startX == (e.getX()/75))&&((((e.getY()/75)-startY)==1)||((e.getY()/75)-startY)==2))
            {
                if((((e.getY()/75)-startY)==2)){
                    if((!piecePresent(e.getX(), (e.getY())))&&(!piecePresent(e.getX(), (e.getY()+75)))){
                        validMove = true;
                    }
                    else{
                        validMove = false;
                    }
                }
                else{
                    if((!piecePresent(e.getX(), (e.getY()))))
                    {
                        validMove = true;
                    }
                    else{
                        validMove = false;
                    }
                }
            }
            else{
                validMove = false;
            }
        }

I have no idea what to e.getX()/75 and e.getY()/75 should be doing.

Any ideas?

Insertion errors encountered for java.io.IOException

I’m relatively new with Apache Beam Pipeline and am trying to modify an existing beam pipeline code by inserting a parameter in a ‘Data’ class and retrieving it to do further calculations in subsequent steps, as below.

public class Data {  
  @JsonProperty("loss")
  private double loss;

  public double getLoss() {
    return loss;
  }

  public void setLoss(double loss) {
    this.loss = loss;
  }
}

I’ve also made changes to the schema in data.json as below:

final TableSchema dataSchema = SchemaLoader.load("/data.json");

writeIntoBigQuery(options.getDataTableName(), dataSchema, Data, new InputToTableRow());

However, I’m still getting a runtime error (I only reproduced the first few lines, the rest seem to be complaining about more or less the same thing). Initially I thought it may be because my BigQuery table doesn’t have a ‘loss’ field as part of the table schema and went to add it but its still happening.. Is there somewhere else in the code I should add or modify to make this error go away? Or anything else I should do to get more details on how to troubleshoot?

java.lang.RuntimeException: java.io.IOException: Insert failed: [{"errors":[{"debugInfo":"generic::not_found: no such field.","location":"loss","message":"no such field.","reason":"invalid"}],"index":0}]
        org.apache.beam.sdk.io.gcp.bigquery.StreamingWriteFn.flushRows(StreamingWriteFn.java:106)
        org.apache.beam.sdk.io.gcp.bigquery.StreamingWriteFn.finishBundle(StreamingWriteFn.java:82)
Caused by: java.io.IOException: Insert failed: [{"errors":[{"debugInfo":"generic::not_found: no such field.","location":"loss","message":"no such field.","reason":"invalid"}],"index":0}]

How remove r from output String.JUnit

 I have a file with  (at txt file put it) 
                      0|9
                     - |----------
                      0|0.(0)
                    ____   
                      0
                   -   
                      0 
                    ____    
                      0

I tried to read this file and write result to String,however when begin compression i got it. “r”

>java.lang.AssertionError: 
>Expected: is "  0|9n - |----------n  0|0.(0)n ____n  0n -n  0n ____n   0"
 but: was "  0|9- |----------rn  0|0.(0)rn ____rn  0rn -rn  0rn ____rn   0rn" 

code :

 >  public static void init()  throws IOException{
    >         File file_0_divide_9 = new File("..\DivisionPeriod\src\test\java\com\foxminded\division_period\expe
    >         String line;
    >         int c;
    >             BufferedReader bf = new BufferedReader(new FileReader(file_0_divide_9 ));
    >             line = bf.readLine();
    >             while((c =bf.read()) != -1){
    >                 line+= (char) c;
    >             }
    >             list.add(line);

The list is : private static ArrayList list = new ArrayList();

How i can avoid it?

Hibernate MetaModel cannot be resolved to a type

I’ve generated my metamodels correctly as seen below.
They do not import the actual entity class therefore I get the ” cannot be resolved to a type” compiler error.

package dummy.package;

import javax.annotation.Generated;
import javax.persistence.metamodel.StaticMetamodel;

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(MyClass.class)
public abstract class MyClass_ {

}

as you can see, the class used in the @StaticMetamodel annotation isn’t imported

My assumptions and questions are:

1) Assumption: Both classes have the same package structure, so i’m assuming that we won’t need to import the class (both declared under “dummy.package”) But why do I get the error?

2) The metamodel is actually under “annotations.dummy.package” even though the file says “dummy.package”, that’s a different error (does not match the expected package) Can this be the reason for issue #1 above?

Sphere volume method not working

I have tried many different calculations for trying to get my sphere volume method to work.

My Sphere class is extended from Circle, to get the area from circle, as well as implements my Shape3D interface which allows me to use my volume method.

However, I have tried all of these different formulas for my method and nothing gives me back an accurate volume of a sphere. It is always drastically off.

The one that gets the closest is (4*22*radius * radius * radius )/(3*7); but it is still off.

    //return (4/3) * super.area() * radius;
    //return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
    //return (4*22*radius * radius * radius )/(3*7);
    //return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
    //return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
    //return ( super.area() * getRadius() ) * (4/3);

I am going to attach my code for my Shape abstract class, my Circle class, and my Sphere class, as well as my Shape3D interface.

Maybe I have overlooked something obvious. When I set the radius though and get it the radius returns back normal. So I am not sure why every one of these if completely off.

Shape Class

public abstract class Shape {
    protected String type;

    public Shape (String type) {
        setType(type);
    }// end ctr

    public final String getType ()            {return type;     }
    public final void setType   (String type) {this.type = type;}

    public abstract double area (); // end prototype

    public double getArea () {return area();}

    @Override
    public String toString() {
        String str = "";

        str += type;

        return str;
    }// end descriptor 

}// end shape class

Circle Class

public class Circle extends Shape {
    protected double radius;

    public Circle (double radius) {
        super("Circle");
        setRadius(radius);
    }//end ctr

    public final double getRadius () {return radius;}

    public final void setRadius (double radius) {
        if (radius < 0) {
            System.out.println("Value could not be updated due to negative double.");
        }else 
            this.radius = radius;
    }// end radius setter 

    @Override
    public double area() {
        return (Math.PI * radius * radius );
    }// end method area

    public double circumference () {
        return Math.PI * 2 * getRadius();
    }// end circumference method 

    @Override
    public String toString() {
        String str = "";

        str += String.format("%10s", "Circle:") + " ";
        str += "radius: " + String.format("%.1f", radius) + ", ";
        str += "area: " + String.format("%.2f", area() ) + ", ";
        str += "circumference: " + String.format("%.2f", circumference() );

        return str;
    }// end descriptor 
}// end circle class 

Sphere Class, the error seems to be here in my method volume

public class Sphere extends Circle implements Shape3D {
    public Sphere(double radius) {
        super(radius);
        this.setType("Sphere");
    } // end ctr

    @Override 
    public double area() {
        return super.area() * 4;
    }// end surface area method

    @Override 
    public double volume() {
        double vol;
        double x = 4/3;
        double y = Math.pow(getRadius(), 3);
        double z = Math.PI;
        vol = y * z * x;
        return vol;
        //return (4/3) * super.area() * radius;
        //return (Double)((4*22*getRadius()*getRadius()*getRadius() )/(3*7));
        //return (4*22*radius * radius * radius )/(3*7);
        //return ( (4/3) * (Math.pow(getRadius(), 3) ) / (Math.PI) );
        //return (getRadius() * getRadius() * getRadius() ) * (Math.PI) * (4/3);
        //return ( super.area() * getRadius() ) * (4/3);
    }// end sphere volume

     @Override
    public String toString() {
        String str = "";

        str += String.format("%10s", "Sphere:") + " ";
        str += "radius: " + String.format("%.1f", radius) + ", ";
        str += "area: " + String.format("%.2f", area() ) + ", ";
        str += "circumference: " + String.format("%.2f", circumference() );
        str += ", volume: " + String.format("%.1f", volume() );

        return str;
    }// end descriptor 

} // end class sphere

Shape 3D Interface

public interface Shape3D {
    double volume();

}

Thank you.

Java Queue linked list

in school we are learning about abstract datastructures. Our Task was to implement a linked list into java. For some reason my Queue only dequeues every second elemnt of the Queue. Maybe someone can tell me my mistake because I have no clue anymore. BTW I’m coding using BlueJ so dont wonder about the starting of the programm ๐Ÿ˜€

The dequeue methode

public Car dequeue()
{
    Car c = new Car(head);

    if(c != null){

            if(head.getLast() == tail){

                if(tail == null){

                    head = null;

                    return c;

                }

                else{

                    head = tail;

                    tail = null;

                    return c;

                }  
            }

            else{

                head = head.getLast();

                return c;

            }
    }

    return c;
}

public class Car
{
private String driver;

private Car last;

public Car(String pDriver)
{
    driver = pDriver;
}

The Car object

public Car(Car c)
{
    this.driver = c.getDriverName();

    this.last = c.getLast();
}

public String getDriverName()
{
    return driver;
}

public Car getLast()
{
    return last;
}

public void setLast(Car pLast)
{
    last = pLast;
}
}

Convert S3ObjectInputStream to FileInputStream

Is there a way to convert S3ObjectInputStream to FileInputStream? Or is there a way to use S3ObjectInputStream to read from a file at an offset position? That’s what I’m using the FileInputStream for.

Currently, I have the S3ObjectInputStream stored as an InputStream, but using the skip() method to get to the offset position seems unreliable (I keep getting a NullPointerException when I read after skipping).