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;
}
Related
I'm trying to create a code in java that continuously spits out what the x variable is every 10 milliseconds until the user inputs the String that breaks the loop. I was wondering how to code it.. I have the following right now. The code is currently running and just stopping where the Scanner is suppose to scan for the next line instead of continuously printing out what variable x is.
public static void show() {
while (true) {
if (showWatch.elapsedTime1() > 10) {
System.out.println(x);
showWatch.start();
x = x + 1;
wait(1000);
}
else if (showWatch.elapsedTime1() < 10) {
while (showWatch.elapsedTime1() < 10) {
response = scan.nextLine();
}
if (response.equalsIgnoreCase("STOP")) {
break;
}
else if (showWatch.elapsedTime1() > 10) {
System.out.println(x);
showWatch.start();
x = x + 1;
wait(1000);
}
}
}
}
How do you code a loop that will only continuously print the variable's content until the user types in a word to stop the program?
The scanner will not work if something is printed during typing. But if the interval is big enough it could work. I use the Semaphore so that the Printer-Thread sleeps as long he has no ticket.
public class Printer extends Thread {
public Semaphore stopped = new Semaphore(1);
private int x;
#Override
public void run() {
while (true) {
try {
stopped.acquire();
System.out.println(++x);
stopped.release();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Printer printer = new Printer();
printer.start();
Scanner scan = new Scanner(System.in);
while(true) {
String command = scan.nextLine();
if ("BREAK".equals(command)) {
printer.stopped.acquire(1);
} else if ("RESTART".equals(command)) {
printer.stopped.release(1);
}
}
}
// ************************************************************
// ELEVATOR.java
//
// ELEVAOTR SIMULATION
// PROBLEM: NEED TO FIND A WAY TO AMKE IT SO THAT THE PROGRAM KEEPS RNNING AFTER USER INPUTS
// THIER FIRST DESIRED FLOOR.
// ************************************************************
import java.util.*;
public class Elevator_Simulation {
public static void main (String[] args) {
Person User = new Person();
Floor floors = new Floor();
floors.moveElevator(User.getDesiredFloor());
}
}
class Elevator { //NEEDS SETTER & GETTER METHODS
private int mass=0;
private int capcity=0;
private String name="";
private String color="";
}
class Floor {
ArrayList<Object> floorLevel = new ArrayList<Object>();
Elevator Lift = new Elevator();
Person Man = new Person();
Floor() { //Floors 0-9
floorLevel.add(Lift); //0
floorLevel.add(null); //1
floorLevel.add(null); //2
floorLevel.add(null); //3
floorLevel.add(null); //4
floorLevel.add(null); //5
floorLevel.add(null); //6
floorLevel.add(null); //7
floorLevel.add(null); //8
floorLevel.add(null); //9
}
System.out.println("Elevator is at Floor: " + floorLevel.indexOf(Lift) );
public void moveElevator (int chosenFloor) {
if (chosenFloor > 9) {
System.out.println("Woooooah Buddy! You can only choose 0-9!");
return;
}
if (chosenFloor == floorLevel.indexOf(Lift)) {
System.out.println("Bro you're already on that floor...");
}
while (floorLevel.indexOf(Lift)>chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)-1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
while (floorLevel.indexOf(Lift)<chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)+1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
}
}
class Person {
Scanner scan = new Scanner(System.in);
public int getDesiredFloor() {
int desiredFloor = scan.nextInt();
return desiredFloor;
}
}
Above is an Elevator Simulator Code (before I attempt to make one with a GUI) and my only problem, aside from the obvious beginner flaws, is that I'm having trouble of finding a way to make it so that the program doesn't just end once the user inputs one floor. I at least want the program to run until the user ends it with a command. I'm thinking of using a while loop somewhere but where? Please help and point out anything I should improve in this code.
You can put the while loop around the line
floors.moveElevator(User.getDesiredFloor());
Just add an input check for a value that represents exiting.
TLDR at bottom
I've been assigned a programming project at school to build a percolation model and i've come across an issue which has given me quite some confusion. First off, we were supposed to build an api to run a percolation simulation
public class Percolation{
private int grid[][];
public int size;
QuickFindUF unionFind;
//WeightedQuickUnionUF unionFind;
public Percolation(int n)
{
if(n<1){
throw new IllegalArgumentException ("grid must be larger than 0");
}
grid=new int[n][n];
size=n;
unionFind=new QuickFindUF(size*size);
//unionFind=new WeightedQuickUnionUF(size*size);
//initially set all to blocked
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
grid[i][j]=1;
}
}
}
public void open(int x, int y)
{
grid[x][y]=0;
//Check below to see if you can
//if you are not on the bottom row
if(y>0)
{
if(grid[x][y]==0 && grid[x][y-1]==0){unionFind.union(x+y*size,x+(y-1)*size);}
}
//check to see to the right (x->)
if(x<size-1){
if(grid[x][y]==0 && grid[x+1][y]==0){unionFind.union(x+y*size,x+1+y*size);}
}
//check if can union to the left
if(x>0)
{
if(grid[x][y]==0 && grid[x-1][y]==0){unionFind.union(x+y*size,x-1+y*size);}
}
//check for above
if(y<size-1){
if(grid[x][y]==0 && grid[x][y+1]==0){unionFind.union(x+y*size,x+(y+1)*size);}
}
}
public boolean isOpen(int x, int y)
{
if(x>=size || y>=size){return false;}
if(grid[x][y]==0){return true;}
return false;
}
public boolean isFull(int x, int y)
{
if(x>=size || y>=size){return false;}//if input is out of bounds
for(int i=0;i<size;i++){
if(unionFind.connected(x+y*size,i+((size-1)*size)))
return true;
}
return false;
}
public boolean percolates()
{
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
if(unionFind.connected(i,(size-1)*size+j)){
//System.out.println(i+" "+((size-1)*size+j));
return true;
}
}
}
return false;
}
}
Now, the book kindly provides the quickfindUF and WeightedQuickUnionUF. All the classmates i've talked to have gotten the expected results when timing with a PercolationStats class which we've been instructed to make but my results very greatly. Here's the class
class PercolationStats{
private Percolation perc;
private double[] array;
private int expCount;
public PercolationStats(int gridSize, int numOfExperiments){
if(gridSize <= 0 || numOfExperiments <=0)
throw new IllegalArgumentException("gridSize and numOfExperiments needs to be more than 0");
array=new double[numOfExperiments];
expCount=numOfExperiments;
for(int i=0;i<numOfExperiments;i++){
perc=new Percolation(gridSize);
int count=0;
while(!perc.percolates()){
int x=StdRandom.uniform(gridSize),y=StdRandom.uniform(gridSize);
if(!perc.isOpen(x,y)){
perc.open(x,y);
count++;
}
}
array[i]=(double) count/(gridSize*gridSize);
}
}
public double mean(){
return StdStats.mean(array);
}
public double stddev(){
return StdStats.stddev(array);
}
public double confidenceLo(){
return mean() - ((1.96 * stddev()) / Math.sqrt(expCount));
}
public double confidenceHi(){
return mean()+((1.96 * stddev()) / Math.sqrt(expCount));
}
public static void main(String[] args){
Stopwatch timer=new Stopwatch();
PercolationStats percStats=new PercolationStats(200,100);
System.out.println("mean: "+ percStats.mean() +"stddev: "+percStats.stddev()+" confidence Lo: "+percStats.confidenceLo()+" confidence hi: "+percStats.confidenceHi());
System.out.println(timer.elapsedTime());
percStats=new PercolationStats(200,100);
System.out.println("mean: "+ percStats.mean() +"stddev: "+percStats.stddev()+" confidence Lo: "+percStats.confidenceLo()+" confidence hi: "+percStats.confidenceHi());
percStats=new PercolationStats(2,100000);
System.out.println("mean: "+ percStats.mean() +"stddev: "+percStats.stddev()+" confidence Lo: "+percStats.confidenceLo()+" confidence hi: "+percStats.confidenceHi());
}
}
When I run this with the QuickFindUF, at percStats(200,100), it takes me about 7 seconds, and if I run it at the same 200,100 with WeightedQuickUnionUF, It takes about 50+ seconds?? I was quite certain that the weighted quick union was supposed to be faster, and it's not just a matter of getting unlucky with my horrendous worst case random number generator. I ran it quite a few times and still the results were about the same and I've been staring here at the code for quite a while and can't figure out why my code is so wrong..
TLDR
Correct results, incorrect timing. Slower api is faster for some reason and I can't figure out why. QuickFindUF faster than WeightedQuickUnionUF. (about 7-8 times faster). What am I doing wrong?
Haha I'm dumb. I saw online that others were using a virtual top so I added one and now it works fine :P
Hope you are all well.
Also I'm so sorry for how long winded this is. And I'm new to Java so please forgive me for my lack of knowledge/terminology/Java conventions.
Basically I've created a program which takes user input and moves the vehicle across the surface area. So the user input can be "50 left 4" so that means go 50 meters forward, turn left and go 4 meters forward.
For the vehicle I'm using a paint method on a JPanel. When the vehicle moves forward, it initially jumped from one side of the area to another. I wanted to be able to see it moving meter by meter. So I added a Swing Timer which moves the vehicle 1 meter, pauses for a second, moves the vehicle 2 meter and so on.
Now, the problem is that when I enter the commands "50 left 4", the vehicle simply turns left and then moves 4 meters forward. It ignores the first number command. The same happens when I enter "3 4", it will ignore 3 and just move 4 meters forward. Also when I enter "3 left", it will turn left first and then move 3 meters forward. Now I've got methods which takes the user input, chop it up into an array, feed each element of the array through a loop, check if it's an integer or not. If it is an integer it moves the vehicle forward, if not it turns the vehicle either left or right. That all works fine and I'm happy with it.
So what I thought I'd do is have the class which moves the vehicle implement Runnable so that this method will be executed from a separate thread, making the main thread wait and that way it will won't ignore every command except for the last. But that doesn't work either.
Here is the movement class which moves the vehicle forward 1 meter at a time using a Swing Timer.
It implements Runnable. It's abstract because I needed the run method to take the user input commands as a parameter. Is that what's causing the problem?
public abstract class Movement implements Runnable {
static int count = 0;
static int distance;
public static void moveRover() {
// Every 1 second the timer will move the Rover 40 pixels.
at.translate(0, 40);
}
public static void getDistance(int num) {
distance = num;
}
static Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
moveRover();
count++;
System.out.println(count);
if (count == distance) {
stop();
System.out.println("Timer stopped");
count = 0;
}
}
});
public static void start(int num) {
getDistance(num);
System.out.println("Distance rover will travel: " + distance);
System.out.println("\nTimer started");
timer.start();
}
public static void stop() {
timer.stop();
}
public void run(int num) {
start(num);
}
public Movement(int num) {
System.out.println("Start RUN method");
run(num);
}
And here is the code from another class which runs the for loop and thread:
public static void action(final String[] commands) {
for (int i = 0; i < commands.length; i++) {
if (isInteger(commands[i])) {
int distance = Integer.parseInt(commands[i]);
Movement h1 = new Movement(distance) {
#Override
public void run() {
System.out.println("Empty run method");
}
};
Thread t1 = new Thread(h1);
t1.start();
System.out.println(t1.isAlive());
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Direction.start(commands[i]);
String pos = Direction.getDirection(); // GET DIRECTION
}
}
}
I really appreciate you reading all that, thank you so much!
And thank you to anyone who replies! If you know where I'm going wrong and what I can do to fix it, you're an absolute lifesaver, I really appreciate it :D
So yeah, you need to learn about Threading in Java. You should NEVER use Thread.start() as of Java 1.6 and later. Quite frankly, I'm not even sure why you're using Threads in your for-loop. Ignoring for the moment all of your questionable design choicess, try this code:
public static void action(final String[] commands) {
for (int i = 0; i < commands.length; i++) {
if (isInteger(commands[i])) {
int distance = Integer.parseInt(commands[i]);
new Movement(distance) {
#Override
public void run() {
System.out.println("Empty run method");
}
}.run();
} else {
Direction.start(commands[i]);
String pos = Direction.getDirection(); // GET DIRECTION
}
}
}
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 :)