need assistance with a input issue in java [duplicate] - java

This question already has answers here:
Error in System.out.println
(5 answers)
Closed 4 years ago.
My Task:
Create a class called Icosahedron which will be used to represent a regular icosahedron, that is a convex polyhedron with 20 equilateral triangles as faces. The class should have the following features:
A private instance variable, edge, of type double, that holds the
edge
length.
A private static variable, count, of type int, that holds the
number of Icosahedron objects that have been created.
A constructor that takes one double argument which specifies the edge length.
An
instance method surface() which returns the surface area of the
icosahedron. This can be calculated using the formula 5*√3 edge².
An
instance method volume() which returns the volume of the icosahedron.
This can be calculated using the formula 5*(3+√5)/12*edge³.
An
instance method toString() which returns a string with the edge
length, surface area and volume as in the example below:
Icosahedron[edge= 3.000, surface= 77.942, volume= 58.906]
The numbers in this string should be in floating point format with a field
that is (at least) 7 characters wide and showing 3 decimal places.
Please use the static method String.format with a suitable formatting
string to achieve this. A static method getCount() which returns the
value of the static variable count.
Finally, add the following main method to your Icosahedron class so that it can be run and tested:
public static void main(String[] args) {
System.out.println("Number of Icosahedron objects created: " + getCount());
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++)
icos[i] = new Icosahedron(i+1);
for (int i = 0; i < icos.length; i++)
System.out.println(icos[i]);
System.out.println("Number of Icosahedron objects created: " + getCount());
}
Okay. so heres what i have started on:
import java.util.Scanner;
public class Icosahedron {
private double edge = 0;
private int count = 0;
Scanner input = new Scanner(System.in);
double useredge = input.nextDouble();
System.out.println("Enter Edge Length: ");
}
i receive an error on the last line. i cant use println() what am i doing wrong? or maybe im understanding the question wrong? any guidance would be appreciated.
thanks.

Your Icosahedron class should look like the following:
public class Icosahedron {
private double edge;
private int count;
public Icosahedron(int count) {
this.count = count;
}
public double getEdge() {
return edge;
}
public void setEdge(double edge) {
this.edge = edge;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Icosahedron{edge=" + edge + ", count=" + count + '}';
}
}
And your class containing the main method (I called it MoreProblem):
import java.util.Scanner;
public class MoreProblem {
public static void main(String[] args) {
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++) {
icos[i] = new Icosahedron(i+1);
Scanner input = new Scanner(System.in);
System.out.println("Enter Edge Length: ");
double userEdge = input.nextDouble();
icos[i].setEdge(userEdge);
}
for (Icosahedron icosahedron : icos) {
System.out.println(icosahedron);
}
System.out.println("Number of Icosahedron objects created: " + icos.length);
}
}

Related

Why is array giving a wrong value when using two classes?

I have this code here.
public class ArrayChallenge {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of integers: ");
int num = kb.nextInt();
int [] returnedArray = readIntegers(num);
System.out.println("Ascending Order: " + printAsc(returnedArray));
}
public static int [] readIntegers(int count){
int [] values = new int[count];
for(int i=0; i<count; i++){
System.out.print("Enter number: ");
values[i] = kb.nextInt();
}
return values;
}
public static int [] printAsc(int [] theArray){
Arrays.sort(theArray);
return theArray;
}
The code above works perfectly fine. I have only one class but several static methods and during calling the method printAsc(returnedArray), the program will return a set of arrays in a format just like using .toString
I took this code to a next level using two classes and making the static methods to instance methods. However when i print the arrays. It prints these values [I#643b1d11
Here is my code below:
Main Class
public class Main {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the number of elements: ");
int num = kb.nextInt();
int numArrays [] = new int[num];
Minimum minimum = new Minimum();
int [] returnedArrays = minimum.readIntegers(numArrays);
int returnedMin = minimum.findMin(returnedArrays);
System.out.println("Minimum Value: " + returnedMin);
System.out.println("Ascending Arrays: " + minimum.arrayAsc(returnedArrays));
}
}
Minimum Class
public class Minimum {
public int [] readIntegers(int [] numArrays){
System.out.println("Enter " + numArrays.length + " integers:");
for(int i=0; i< numArrays.length; i++){
numArrays[i]=Main.kb.nextInt();
}
return numArrays;
}
public int findMin(int [] numArrays){
int max = Integer.MAX_VALUE;
for(int i=0;i<numArrays.length;i++){
if(max>numArrays[i]){
max = numArrays[i];
}
}
return max;
}
public int [] arrayAsc(int [] numArrays){
Arrays.sort(numArrays);
return numArrays;
}
}
How did the result of my arrays became like that? Can someone explain the process to me? Much appreciate.
Also, i used the debug method because im using Intellij, It didnt really show anything.
The way you are using printAsc, you need to change its definition to return a String.
public static String printAsc(int [] theArray){
Arrays.sort(theArray);
return Arrays.toString(theArray);
}
If you do not want to change the definition of printAsc, you need to call it as follows:
System.out.println("Ascending Order: " + Arrays.toString(printAsc(returnedArray)));
You can't just print an Array and expect it to read out all the values. When printing, Java casts the value into a String. By default, when dealing with Objects, Java will simply print the name of the Object's class and its Hash value. This is what you see. You can read more about it here.
If you want to parse the Array into a String that hold all the members of the Array, you might want to take a look at the Arrays.toString method (and how to use it).

I can not understand why my console is not showing any of my output [duplicate]

This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 3 years ago.
my console doesn't seem to be showing any output on my projects, on some, it does at first. I am new to this so I don't understand it, this is an example of my code
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
}
public void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Replace your main method with the following code and it should work as you are expecting:
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
}
The reason why it didn't work for you is because you have missed to call the methods you have created in the class. I have added the following lines in the main method to complete that missing part:
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
None of your methods are static, so you'll need to create an instance of your TestAmazing class, and call methods via your instance.
That might look something like:
public static void main(String args[]) {
TestAmazing test = new TestAmazing();
test.roomtemp();
test.bonusball();
// etc...
}
Comment from QA:
this worked thank you! do I have to always do this and put it in the
same place? – Joe Emery
Not necessarily. It depends on the requirements of your program. If all of your methods are STATIC then you don't need an instance of your class. In that case, then you'd simply call all of your methods directly from main, like this:
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
roomtemp();
bonusball();
currentpopulationofchina();
gameloadingstatus()
}
public static void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public static void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public static void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public static void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Notice how every method has static in its declaration.

Inputting random integers into a file and sorting them into another file? FileIO

I'm trying to create a FileIO where random numbers are placed into a .txt file and outputted, sorted in another .txt file. I have a bubble sort code that can sort numbers & I have another code that makes a .txt file. I'm just not sure how I'd implement these 2 together.
Here's my fileIO code:
public static void main(String[] args) {
File file = new File("test.txt");
//Writes name and age to the file
try {
PrintWriter output = new PrintWriter(file);
output.println("Rober");
output.println(27);
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
//Reads from the file
try {
Scanner input = new Scanner(file);
String name = input.nextLine();
int age = input.nextInt();
System.out.printf("Name: %s Age %d\n", name, age);
} catch (FileNotFoundException ex) {
System.out.printf("ERROR: %s\n", ex);
}
}
And here is my bubble sort code:
public static void main(String[] args) {
Random num = new Random();
//Creating an array for 10 integers
int [] number = new int [10];
System.out.print("Random Numbers:");
/*Display the unsorted numbers in a random order.
These numbers range from 0 to 100
*/
for (int d = 0 ; d<number.length ; d++){
/* We add a "+1" to the nextInt(100) here because then the numbers
will only range from 0 to 99.
*/
int RandomG = num.nextInt(100)+1;
number[d] = RandomG;
System.out.print(" " +RandomG);
}
//Display the sorted numbers
System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
}
public static int [] BubbleSortAsceMethod(int[] number){
int placeholder;
for(int i = 0 ; i < number.length-1 ; i++){
for ( int x = 1 ; x < number.length-i ; x++){
/*If the first number in the sequence is greater than the second
number, than save the first number of sequence in placeholder
and place the second number in the first numbers position, and
put the placeholder in the second numbers position (SWAP).
*/
/*
Since this is saying that when the first term is bigger than the
2nd term, the sequence will increase. If we flip the relational
operator, the sequence will decrease.
*/
if ( number[x-1] < number[x]){
placeholder = number[x-1];
number[x-1] = number[x];
number[x] = placeholder;
}
}
}
return number;
}
I'm kinda new to all this java stuff so please go a bit easy on me! Any help at all is appreciated :)
As the data contained in the file will consist of a pair of values: The name (String) and the age (int), you will need to retain their relationship. The best way of doing this would be to create a Class to represent the data. Eventually you want to sort the data on age using your BubbleSort method. While practically this would not be your first choice to sort data, I assume that this is a requirement. The BubbleSort method you have sorts an int[] by comparing each entry against it's immediate neighbor. With int being primitive, you can directly compare each element using the < operator.
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return name + System.lineSeperator() + age;
}
#Override
public int compareTo(Person person) {
return this.age - person.age;
}
}
You may want to implement the Comparable interface to compare Objects; in which the interface must be implemented by Overriding the compareTo(Person person) method. You can impose sorting on age by returning the difference in age. This is not the only way you can impose the order you want; you may wish to compare directly using the getAge() of each Object or create a Comparator object.
Using the Comparable interface does allow you to make your BubbleSort class more generic, however (though the array must be of Objects that implement the interface; hence no primitive types).
public class BubbleSort {
public static <T extends Comparable> T[] BubbleSortAsceMethod(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int x = 1; x < array.length - i; x++) {
if (comparator.compare(array[x - 1], array[x]) < 0) {
T placeholder = array[x - 1];
array[x - 1] = array[x];
array[x] = placeholder;
}
}
}
return array;
}
}
You will notice that this sort method has some slight differences from your original, namely the BubbleSortAsceMethod method signature with the introduction of generic type parameters. Once again, this is completely optional, though this does give you the flexibility to use this method in the future for other arrays of Classes that extend the Comparable interface.
If you don't want to use generics or the Comparable interface, you will need to change the method signature and if statement.
You're method signature should instead look like public static Person[] BubbleSortAsceMethod(Person[] array) and the if statement if (array[x-1].getAge() < array[x].getAge())
This can give you an illustration of it working, though this does not consider the file io which should be simple to implement from what you have done already.
static Random random = new Random();
public static void main (String args[]) {
int size = 100;
Person[] peopleArray = new Person[size];
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
peopleArray[i] = new Person(name, age);
}
peopleArray = BubbleSort.BubbleSortAsceMethod(peopleArray);
}
Note that this conforms, at least as much as possible, to the code you have implemented this far. If the BubbleSort and use of arrays are not critical, data structures that implement the List interface, such as ArrayList, can allow you to implement this much cleaner. This does not use the BubbleSort method at all.
public static void main (String args[]) {
int size = 100;
ArrayList<Person> people = new ArrayList<>();
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
people.add(new Person(name, age));
}
peopleList.sort(Person::compareTo);
//or, if you don't want to implement comparable
peopleList.sort(Comparator.comparing(Person::getAge));
}
Appendix:
Used for illustrative purposes: Generates a name of a set length (randomly).
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static String generateName(int length) {
if (length > 0) {
return alphabet[random.nextInt(alphabet.length)] + generateName(length - 1);
}
return "";
}

Implementation of Radix sort in Java using Nodes instead of integers

I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].

Returning String Methods in Java?

I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()

Categories

Resources