Java Prime Numbers Client/Server - java

I am making an application that tells you if the number you enter is prime or not.The problem I have is that it only asks once and terminates the program.
How could I do to keep asking numbers and the program ends when enter the number 0?
Updated Code.
public class numerosPrimos {
public static String CheckPrimo(int numero){
int contador = 0;
int residuo = 0;
int divisores = 0;
for (contador=1;contador<=numero;contador++)
{
residuo=numero%contador;
if(residuo==0)
{
divisores++;
}
}
if(divisores>=3)
{
return "El numero "+numero+" no es primo";
}
else
{
return "El numero "+numero+" es primo";
}
}
}
Thank you in advance guys!

Simple said:
Put everything in the main method of the client into a while loop and add an if-branch to jump out of the programm if the given number is 0.

Have you tried putting a loop into your client program (instead of calling System#exit after just one number)?
And on the server-side, don't close the server socket. If you do, no one can connect anymore.

The problem was on my class, I got all declared as static, I corrected it starting the variables inside "CheckPrimo" like this:
public class numerosPrimos {
public static String CheckPrimo(int numero){
int contador = 0;
int residuo = 0;
int divisores = 0;
for (contador=1;contador<=numero;contador++)
{
residuo=numero%contador;
if(residuo==0)
{
divisores++;
}
}
if(divisores>=3)
{
return "El numero "+numero+" no es primo";
}
else
{
return "El numero "+numero+" es primo";
}
}
}
Thank you for your help :)

Related

FRQ High Scores Part B: I'm getting a "missing a return statement" when the returns are in the for loop? Shouldn't the returns be reached?

I'm a high schooler in apcs and I'm trying to practice these for the test. The code should return whether a new object was created. Also, the moveUp method doesn't allow me to call it using the scoreboard list (e.g. "scoreboard.move(int x)". Please explain why I'm wrong, but don't solve it.
public boolean newScore(String name, int score)
{
/* Implement your answer to part (b) here */
for (int ind = 0; ind < scoreboard.size(); ind++) {
Player player = scoreboard.get(ind);
if (player.getName().equalsIgnoreCase(name)) {
player.updateScore(score);
moveUp(scoreboard.indexOf(player));
return true;
} else {
Player p = new Player(name, score);
scoreboard.add(p);
p.updateScore(score);
moveUp(scoreboard.indexOf(p));
return false;
}
}
}

Why Eclipse keeps crashing when i try to calculate this loop?

the program is about to calculate the average of numbers. Sorry ==if no number is inputted
public static void main(String[] args) {
int summa=0;
int antal=0;
String indata= showInputDialog("Ange ett tal");
while(indata!=null) {
int tal=Integer.parseInt(indata);
antal= antal+1;
summa=summa+tal;
}
if(antal>0) {
double medelv=(double)summa/(double)antal;
showInputDialog("Medelvärde av de 5 talen"+ medelv);
}
else {
showMessageDialog(null,"du måste ange ett tal" );
}
}
It looks like your while loop is causing the crash because the variable indata is never changed inside of it, meaning that the loop will run indefinitely with no alternate path to exit it.
while(indata!=null) {
int tal=Integer.parseInt(indata);
antal= antal+1;
summa=summa+tal;
}

Count wrong answer

I am trying to create java application.
It ask questions and have 4 choices for each question.
I want to count total right and wrong answers selected by the user.
I am using function like this-
public void checkAnswer(String choice)
{
int correctcount=0;
int wrongcount=0;
if(counter==1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correct count + 1;
} else {
wrongAnswerDisplay();
wrongcount = wroungcount + 1;
}
}
else if(counter==2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
} else {
wrongAnswerDisplay();
}
}
Basically I hardcoded answers for each question.
For e.g- For this question, correct answer is "A". so I said if its "a" call the correct answer function else wrong answer in question#1. Counter variable is to display next questions
How can i calculate total right and wrong answer of all question. I have allowed users to select another option if they answer wrong, so they don't get to next question until they select right answer. But every time when they select wrong answer counter will add more numbers it should allow only 1 addition and stop there.
Also, lets says i selected wrong answer, I won't get next question until i hit continue button, and continue button appears only when i select correct answer. So if i select wrong answer 2 times, counter will be 2. It should work as i select wrong answer even three times, total wrong answer count should be just 1. and person will always select correct answer once for each question because continue button doesn't appear until then. So it should not increase correct counter if wrong answer was selected first.
Sorry I am a new programmer. Please help.
package org.test.main;
import java.util.Scanner;
public class TestMain {
public int correctcount = 0;
public int wrongcount = 0;
public int counter = 1; // lets assume you have counter as 1 to start with
public void checkAnswer(String choice) {
if (counter == 1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
} else {
wrongAnswerDisplay();
wrongcount = wrongcount + 1;
}
} else if (counter == 2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
} else {
wrongAnswerDisplay();
wrongcount = wrongcount + 1;
}
}
}
private void wrongAnswerDisplay() {
System.out.println("Wrong");
}
private void correctAnswerDisplay() {
System.out.println("Correct");
}
public static void main(String[] args) {
TestMain testM = new TestMain();
Scanner scanNext = new Scanner(System.in);
for(int i = 0; i < 2;i++) {
System.out.print("Question#"+(i+1)+": ");
String ans = scanNext.nextLine();
testM.checkAnswer(ans);
testM.counter++;
}
System.out.println("Number of Correct Answer:" + testM.correctcount);
System.out.println("Number of Wrong Answer:" + testM.wrongcount);
}
}
Make your correctcount and wrongcount as instance variable. because every time you call the method checkAnswer(), 0 will be assigned in the 2 variables you created in your method.
I tried to simulate your logic. so try this. The numbers of question and the answers are hardcoded. so change it in your logic to be dynamic. I write this code to understand how the incrementation works.
It is a really good thing that you have started using communities like Stackoverflow.
Form the question it is clear that there is a continue button which will be enabled only if you select the correct answer. (Then there is no point in counting correct answers since with such a button, at the end you will have all the questions answered correctly. Anyway if you really want this logic to work try the following.)
Let's create a method incrementWrongCount() to increment the variable wrongcount.
public class AnswerTester{
int correctcount = 0;
int wrongcount = 0;
/*Following variable indicates whether you have selected any wrong answers before
selecting the right answer. Obviously its default value is false since you
have selected no wrong answers (in fact no answers) when you first
you first answers a question*/
boolean wronganswerselected = false;
public void checkAnswer(int counter, String choice){
if(counter==1) {
if (choice.equalsIgnoreCase("a")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
incrementWrongCount();
wronganswerselected = false;//For the next question
enableContinueButton();
} else {
wrongAnswerDisplay();
wronganswerselected = true;//just indicate that you have selected a wrong answer. We will increment wrong count in incrementWrongCount()
disableContinueButton();
}
} else if(counter==2) {
if (choice.equalsIgnoreCase("d")) {
correctAnswerDisplay();
correctcount = correctcount + 1;
incrementWrongCount();
wronganswerselected = false;
enableContinueButton();
} else {
wrongAnswerDisplay();
wronganswerselected = true;
disableContinueButton();
}
}
}
private void incrementWrongCount(){
if(wronganswerselected){//Should increment wrongcount only if the user have selected atleast one wrong answer.
wrongcount = wrongcount + 1;
}
}
private void correctAnswerDisplay(){
System.out.println("Correct..");
}
private void wrongAnswerDisplay(){
System.out.println("Wrong..");
}
public int getCorrectCount(){
return correctcount;
}
public int getWrongCount(){
return wrongcount;
}
}
Its a good practice to use switch instead of if...else if to match a variable against multiple values.

Euler's Project #3 Output Error

I am currently attempting problem 3 of Euler's Problems and I have run into the problem where when the below code is compiled, all I get is "1" as output even though the for loop makes it run over multiple times. I have lowered the number down to 30 to try to find the problem but I have not found it. Looking at other solutions, my solution's logic is exactly the same.
public class eulerproblem3
{
public static void main(String[]args)
{
int current = 1;
for (int test=1;test==30;test++)
{
if ((30%test)==0)
{
boolean a = testPrime(test);
if ((a==true)&&(test==current))
{
System.out.println(current);
}
}
}
}
private static boolean testPrime(long test1)
{
for(long ref=2; test1==ref; ref++)
{
if ((test1%ref)==0)
{
return false;
}
}
return true;
}
}
The conditions of your fors will be always false. You probably want something like
for (int test = 1; test < 30; test++)

Variables in Methods don't save their value

I'm having a problem with 2 variables, the first of them is called "Num_Viajes" and the function is increasing it value by one everytime I call the method "de_Viaje". The second is called "Total_Pasajeros" and the function is make an addition between itself and another variable called "Num_Pasajeros", both variables are int.
Anyway the thing is, when I call the Method "Reporte_Final" both variable should print their results, for example: If I call the Method "de_Viaje" 2 times and I enter the value "45" for the variable "Num_Pasajeros" the program should return this:
Num_Viajes = 2
Total_Pasajeros = 90
But instead, it returns:
Num_Viajes = 1
Total_Pasajeros = 45
So I think that's because the program is not saving the values of my variables, so they are always restarting. How can I fix this?
Here's the code:
import javax.swing.*;
public class Empresa_Autobuses
{
String Tipo_Vehiculo;
String Analisis_Viaje;
int Num_Pasajeros;
int Num_Viajes;
int Total_Pasajeros;
int Prom_Pasajeros;
public static void main(String ... args)
{
boolean Bandera_Falsa = true;
Empresa_Autobuses Viajero = new Empresa_Autobuses();
do
{
Viajero.de_Viaje();
Viajero.Reporte_Viaje();
Viajero.Solicitud_Viaje();
Viajero.Reporte_Final();
}while(Bandera_Falsa == true);
}
public void de_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
Tipo_Vehiculo = JOptionPane.showInputDialog("Selecciona el Tipo de Autobus (G = Grande, P = Pequeño").toUpperCase();
Num_Pasajeros = Integer.parseInt(JOptionPane.showInputDialog("Introduzca el Número de Pasajeros: "));
if(Tipo_Vehiculo.equals ("G"))
{
if(Num_Pasajeros > 60)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 30)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else if(Tipo_Vehiculo.equals ("P"))
{
if(Num_Pasajeros > 20)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 10)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
Viajero.Solicitud_Viaje();
}
}
public void Reporte_Viaje()
{
JOptionPane.showMessageDialog(null, "Reporte de Viaje\nEl Tipo de Autobus fue: "+Tipo_Vehiculo+"\nEl Total de Pasajeros en el Viaje fue de: "+Num_Pasajeros+"\n"+Analisis_Viaje);
}
public void Solicitud_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
String Solicitud;
boolean flag = true;
do
{
Solicitud = JOptionPane.showInputDialog("¿Quiere realizar otro Viaje? (Y/N)").toUpperCase();
if(Solicitud.equals ("Y"))
{
Viajero.main();
}
else if(Solicitud.equals ("N"))
{
flag = true;
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
flag = false;
}
}while(flag == false);
}
public void Reporte_Final()
{
Prom_Pasajeros = Total_Pasajeros / Num_Viajes;
JOptionPane.showMessageDialog(null, "El Número de Viajes realizados fue de: "+Num_Viajes+"\nEl Total de Pasajeros fue de: "+Total_Pasajeros+"\nEl Promedio de Pasajeros fue de: "+Prom_Pasajeros);
System.exit(9999);
}
}
The problem does not seem to be where you think it is. What happens when Num_Pasajeros>60? Why is the increment within a "then" block if it should always happen?
Edit
It appears very likely that the problem is that you run your main procedure from within your program. This second invocation creates a whole new object that is not related to the one you've been working with! Don't do that, and you should probably be fine. You have some issues with your Swing threading, but you probably shouldn't think about that yet.
Should debug it, take a break point # Empresa_Autobuses Viajero = new Empresa_Autobuses(); and see whats happening what case (if/else branch) is running/executing, what are your variable actual values...
Anyway if you observe it carefully: if the care type is P, then you total_pasajeros will not summed with num pasarejos.
Tipo_Vehiculo.equals ("P"))
And +1 for the Java Code Convention: http://web.archive.org/web/20140222045352/http://www.oracle.com/technetwork/java/codeconv-138413.html
(You make everybody job easier here if you keep youeself to that)
p.s: I do not know Italian language but common sense suggest these....

Categories