I tried searching on here for something similar, but failed to find it, maybe using wrong keywords let me know, but here is the deal.
I am fairly new with java and wanted to make something useful myself.
My idea was to create a random number picker within a range with.
So let's say range is from 1-50, and I want 5 random number in this range, and they have to be all different. I have worked with Random before, but not sure what I am doing wrong, here is the code I have so far, please push me in the right direction if possible.
I want to create an array or list with the number, or is there a better way to do this?
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
rnd(start,end);
int[] randomArrays = new int[c];
for(int i = 0; i>randomArrays.length; i++){
randomArrays.add();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
sorry if my code is messy.
At the moment I can't even get the random number to be added into the array
Try this, I did explain to you what is wrong with comments at the code, read them.
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static int[] randomArrays; // You need to declare the vector as an instance variable, otherwise it will disappear when the method it's done.
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
randomArrays = new int[c];
for(int i = 0; i<randomArrays.length; i++){ // The condition was wrong
int numberToAdd = rnd(start,end);
randomArrays[i] = numberToAdd; //You are not using an ArrayList, vector has not the method add(), you have to add new element to the vector throughout its index
}
}
public static void main(String[] args) {
Randomizer rdm = new Randomizer();
rdm.nPicker();
for(int number:rdm.randomArrays) {
System.out.println(number);
}
}
}
Thank you everyone for your advices and hints. In the end I think I managed to get the code how I wanted with the code below.
Tell me if you see an error in this method, or if it has a way that is not allowed in java.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
List randomnumbers = new ArrayList();
for(int i = 0; i<c; i++){
int numb = rnd(start,end);
if(randomnumbers.contains(numb)){
break;
}else{
randomnumbers.add(numb);
}
}
randomnumbers.forEach(System.out::println);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
ok in the end i changed the loops as following:
for(int i = 0; i<c;){
int numb = rnd(start,end);
while(!(randomnumbers.contains(numb))){
randomnumbers.add(numb);
i++;
}
}
randomnumbers.forEach(System.out::println);
}
seems to work fine this way
Related
getting error that variable not found. not able to figure out exact problem. tried resetting preferences also in bluej.
import java.util.*;
class Electricity
{
public void Initialization()
{
int omr = 0;
int nmr = 0;
int cr = 0;
int rent = 0;
double cost = 0.0;
double sc = 0.0;
}
public void input()
{
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
}
public void calculate()
{
cr = nmr - omr;
}
public static void main()
{
Scanner sc = new Scanner(System.in);
}
}
This is not error in bluej it's problem with the code
I'm guessing you are a student
The code is not working since variable only exist inside the method it was created in
You are trying to access variable defined in different methods.
Inside the input() method you trying to access variable that you defined in Initialization() method But it does not exist in input()
Jest to make this code work put all your code inside the main() method .
Or pass the method the variables they using from another method and of course you need to call those methods from main method but seems like you have some more learning to do to make the second option to work.
Good luck.
Somthing like that.
import java.util.Scanner; // Import the Scanner class
public class Main
{
static int calculate(int nmr, int omr)
{
int cr = nmr - omr;
return cr;
}
public static void main(String[] args)
{
int omr = 0;
int nmr = 0;
// int cr = 0;
// int rent = 0;
// double cost = 0.0;
// double sc = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
System.out.println("The resaults: " + calculate(nmr, omr));
}
}
package booking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CarProfile {
static int year;
static int cylinders;
static int plateNum;
public static void main(String[] args) {
int reg = 1;
ArrayList <CarProfile> list = new ArrayList <CarProfile>();
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while(reg == 1) {
System.out.println("Enter manf. year");
year = sc.nextInt();
System.out.println("Enter num. of cyl");
cylinders = sc.nextInt();
System.out.println("Enter plateNum");
plateNum = sc.nextInt();
System.out.println("If you wish to register another car press 1, otherwise press anything");
reg = sc.nextInt();
}
Arrays.toString(list.toArray());
}
}
This is the code. I also tried to use a for loop with System but didn't get any luck there either. So what am I missing here?
I don't know what else to type, it is a really simple question.
You aren't calling System.out.println on the code, The code doesn't knows its suppose to print it out. so replace
Arrays.toString(list.toArray());
With
System.out.println(Arrays.toString(list.toArray()));
Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}
I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}
Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class