java assignment in string by using charAt() - java

import java.util.Scanner;
/**
* #(#)wefeqwrf.java
*
* wefeqwrf application
*
* #author
* #version 1.00 2013/11/15
*/
public class wefeqwrf {
public static void main(String[] args) {
// TODO, add your application code
Scanner scan= new Scanner(System.in);
String number = "000";
String a;
int count=0;
for(int i=0;a!="-1";i++)
{
for(int k=0;k<3;k++){
a=scan.next();
a.charAt(0)= number.charAt(k);
if(number.equals("110"))
{
System.out.print("Tebrikler!=110");
count++;
}
else
{
System.out.print("Maalesef olmadı:" + number);
}
}
}
}
}
It gives the error:
error: unexpected type at this code: `a.charAt(0)= number.charAt(k);`
how can I assign the content of a to the specified index of number?
and when I changed the string a to the char a scan.next() does not work why and what can I do is there a any scanner method for char?

You should do it this way:
a = number.charAt(k) + a.substring(1);
You can't assign something to a method. Methods only return something.

Related

Getting ArrayOutOfBounds and NullPointerException But I don't Know Why

I am testing a program I wrote for an assignment, and right now it's testing at 50% against test cases. I get the following errors when I submit, but I can't figure out why. I tried changing some pieces of code and retesting, but no matter what I do I get the same errors, so I must be completely missing what I should be looking for. Here is the CSV file from which the data is being pulled -
CSV Data File. Here are the errors I get:
Here is my code:
Main class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.io.File;
import java.util.Scanner;
/**
*
* #author Michal
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception{
Scanner kb = new Scanner(System.in);
boolean flag = true;
System.out.println("Welcome to the Car Database");
System.out.println("Enter the size of the array:");
int size = Integer.parseInt(kb.nextLine());
CarDatabase db1 = new CarDatabase(size);
System.out.println("Enter the name of the input file:");
String userFile = new String(kb.nextLine());
db1.readFile(userFile);
while (flag) {
System.out.println("Enter make, mpg, weight, all, or quit:");
String command = kb.nextLine();
if (command.equals("make")) {
System.out.println("Enter the make:");
String make = kb.nextLine();
db1.displayMake(make);
} else if (command.equals("mpg")) {
System.out.println("Enter the mpg range:");
double mpgLow = Double.parseDouble(kb.nextLine());
double mpgHigh = Double.parseDouble(kb.nextLine());
db1.mpgRange(mpgLow, mpgHigh);
} else if (command.equals("weight")) {
System.out.println("Enter the weight range:");
double weightLow = Double.parseDouble(kb.next());
double weightHigh = Double.parseDouble(kb.next());
db1.weightRange(weightLow, weightHigh);
} else if (command.equals("all")) {
CarDatabase.displayAll();
} else if (command.equals("quit")) {
flag = false;
}
}
}
}
CarDatabase class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
* #author Michal
*/
public class CarDatabase {
private static Car[] database;
public CarDatabase(int s) {
this.database = new Car[s];
}
public boolean isFull() {
boolean full = true;
for (int i = 0; i < database.length; i++) {
if (database[i] == null) {
full = false;
}
}
return full;
}
public static void readFile(String f) throws FileNotFoundException {
File file = new File(f);
int lineNum = 0;
Scanner sc = new Scanner(file);
String csvSplitBy = ",";
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] carData = line.split(csvSplitBy);
String model = carData[0];
String make = carData[1];
double mpg = Double.parseDouble(carData[2]);
int weight = Integer.parseInt(carData[3]);
int year = Integer.parseInt(carData[4]);
database[lineNum] = new Car(model, make, mpg, weight, year);
lineNum++;
}
}
public static void displayMake(String m) {
for (int i = 0; i < database.length; i++) {
if (database[i].make.equals(m)) {
database[i].toString();
}
}
}
public static void mpgRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if (database[i].mpg >= l && database[i].mpg <= h) {
database[i].toString();
}
}
}
public static void weightRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if ((database[i].weight >= l) && (database[i].weight <= h)) {
database[i].toString();
}
}
}
public static void displayAll() {
for (int i = 0; i < database.length; i++) {
database[i].toString();
}
}
}
Car class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
/**
*
* #author Michal
*/
public class Car {
public String model, make;
public double mpg;
public int weight, year;
public Car(String md, String mk, double umpg, int w, int y) {
model = md;
make = mk;
mpg = umpg;
weight = w;
year = y;
}
public String toString() {
return "Model:" + model + " Make:" + make + " mpg:" + " weight:" + " year:" + year;
}
}
Here is a sample from the CSV file if you cannot see it:
You are probably getting to the End of File and you try to split. The array then doesn't have any value. Make sure there is no blank line at the end of your database, or put a check in your readfile to make sure that if the carData.length == NUMBER OF DATA FIELDS
Update
You also should check to make sure that you don't pass the total number of database entries you have. So do:
while(sc.hasNextLine() && lineNum < database.length) {
ArrayIndexOutOfBoundsException is thrown in very specific circumstances:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
In your code, you assume that each row in your csv has the same number of fields.
You're also assuming that the size of database array matches the number of cars in your file. Since you don't create your database array entries until you read them from the file - but you pre-initialize the size database array, you could end up reading past the end of your database if the number of records in the CSV is larger than the value you initialize for the database size.

Error: unreported exception IllegalMoveException; must be caught or declared to be thrown [duplicate]

This question already has answers here:
Unreported exception java.sql.SQLException; must be caught or declared to be thrown? [duplicate]
(4 answers)
Closed 6 years ago.
No idea what I'm doing wrong. If I could get some help that would be fantastic. Here's the class with the error:
import java.util.Scanner;
/** The solitaire card game Idiot's Delight. */
public class IdiotsDelight {
/** For reading from the console. */
public static final Scanner INPUT = new Scanner(System.in);
/** The four Stacks of Cards. */
private Stack<Card>[] stacks;
/** The Deck of Cards. */
private Deck deck;
/** Create and shuffle the Deck. Deal one Card to each Stack. */
public IdiotsDelight() {
deck = new Deck();
deck.shuffle();
stacks = new Stack[4]; // This causes a compiler warning
for (int i = 0; i < 4; i++) {
stacks[i] = new ArrayStack<Card>();
}
deal();
}
/** Deal one Card from the Deck onto each Stack. */
public void deal() {
for (Stack<Card> s : stacks) {
s.push(deck.deal());
}
}
/** Play the game. */
public void play() {
while (true) {
// Print game state
System.out.println("\n" + this);
// Check for victory
boolean done = true;
for (Stack<Card> s : stacks) {
if (!(s.isEmpty())) {
done = false;
break;
}
}
if (done) {
System.out.println("You win!");
return;
}
// Get command
System.out.print("Your command (pair, suit, deal, or quit)? ");
String command = INPUT.nextLine();
// Handle command
if (command.equals("pair")) {
removePair();
} else if (command.equals("suit")) {
removeLowCard();
} else if (command.equals("deal")) {
deal();
} else {
return;
}
}
}
/**
* Remove the lower of two Cards of the same suit, as specified by
* the user.
*/
public void removeLowCard() throws IllegalMoveException {
System.out.print("Location (1-4) of low card? ");
int i = INPUT.nextInt();
System.out.print("Location (1-4) of high card? ");
int j = INPUT.nextInt();
INPUT.nextLine(); // To clear out input
stacks[i - 1].pop();
}
/**
* Remove two Cards of the same rank, as specified by the user.
*/
public void removePair() throws IllegalMoveException {
System.out.print("Location (1-4) of first card? ");
int i = INPUT.nextInt();
System.out.print("Location (1-4) of second card? ");
int j = INPUT.nextInt();
INPUT.nextLine(); // To clear out input
stacks[i - 1].pop();
stacks[j - 1].pop();
}
public String toString() {
String result = "";
for (int i = 0; i < 4; i++) {
if (stacks[i].isEmpty()) {
result += "-- ";
} else {
result += stacks[i].peek() + " ";
}
}
return result + "\n" + deck.size() + " cards left in the deck";
}
/** Create and play the game. */
public static void main(String[] args) {
System.out.println("Welcome to Idiot's Delight.");
IdiotsDelight game = new IdiotsDelight();
game.play();
}
}
Error is in the play() method, specifically on these 2 lines with the same error:
removePair();
removeLowCard();
IllgalMoveException class just in case it's needed:
/** Thrown when a player attempts an illegal move in a game. */
public class IllegalMoveException extends Exception {
}
Catch an exception using try-catch block, like this:
//...
try{
removePair();
}catch(IllegalMoveException e){
//...
}
//...
 
//...
try{
removeLowCard();
}catch(IllegalMoveException e){
//...
}
//...

Junit - Testing constructor without parameters?

I have to create JUnit test cases for this class. One of the tests is to test the constructor of the ShannonsTheorem class. Are there ways to test a constructor that does not have any parameters?
There is another class named ShannonsModel that also needs to have its constructor tested. According to the UML we were provided there are no parameters on that constructor either.
Thanks!
package network;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ShannonsTheorem {
ShannonsModel model = new ShannonsModel();
Scanner kb = new Scanner(System.in);
/**
* default constructor for ShannonsTheorem class.
*
*/
public ShannonsTheorem()
{
}
/**
* Method to return the value in bandwidth variable.
* #return
*/
public double getBandwidth()
{
return model.getBandwidth();
}
/**
* getSignalToNoise method to return the signalToNoise value in variable signalToNoise
* #return
*/
public double getSignalToNoise()
{
return model.getSignalToNoise();
}
/**
* main method for ShannonsTheorem
* #param args
* while loop to handle user input to continue or end program
*/
public static void main(String[] args)
{
try {
Scanner kb = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
ShannonsTheorem ST = new ShannonsTheorem();
System.out.println("Enter bandwidth in hertz:");
ST.setBandwidth(kb.nextDouble());
System.out.println("Enter signalToNoise:");
ST.setSignalToNoise(kb.nextDouble());
System.out.println("Values are:");
System.out.println("Bandwidth");
System.out.println(ST.getBandwidth());
System.out.println("SignalToNoise:");
System.out.println(ST.getSignalToNoise());
System.out.println(ST.maxiumumDataRate());
System.out.println("Press any key to make another calculation. Type N or n to Quit");
String s = scan.nextLine();
if(s.equals("n") || s.equals("N")) {
stop = true;
} // end of if
} // end of while loop
}catch (InputMismatchException e){
System.out.println("Input Exception was caught, restart program");
}catch(NumberFormatException e){
System.out.println("Format Exception was caught, restart program");
}
}
/**
* public method to retrieve the maximum data rate. This method makes a call to the private method
* under the same name.
* #return
*/
public double maxiumumDataRate()
{
// calling to the private method maxiumumDataRate. Storing the return value from said method into variable result
// when this public method is called it will return the result from the private method,
double result = model.maxiumumDataRate();
System.out.print(model.toString());
return result;
}
/**
* setBandwidth method to set the bandwidth value in hertz
* #param h
*/
public void setBandwidth(double h)
{
model.setBandwidth(h);
}
/**
* setSignalToNoise method to set the signalToNoise variable
* #param snr
*/
public void setSignalToNoise(double snr)
{
model.setSignalToNoise(snr);
}
}
Why do you need to test the constructor ?
You could test that without any modification, the default constructor has some specific fields :
#Test
public void shouldCreateADefaultShannonTheorem() {
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
Object expectedModel = new ShannonsModel();
assertEquals(expectedModel , shannonsTheorem.model);
Object expectedKb = new Scanner(System.in);
assertEquals(expectedKb , shannonsTheorem.kb);
}
or you could test that without any change, the default constructor gives you some results :
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
double expectedbandwith = 0.0;
assertEquals(expectedbandwith , shannonsTheorem.getBandwidth(), 0);
int expectedSignalToNoise = 0;
assertEquals(expectedSignalToNoise , shannonsTheorem.getSignalToNoise(), 0);
int expectedMaximumDataRate = 0;
assertEquals(expectedMaximumDataRate , shannonsTheorem.maxiumumDataRate(), 0);
// ...
that's why it is usefull to do TDD (test first) :
what your application should do ? write the test. // here is the thinking
write the code. // no thinking here !
refactor

Java Calculator with classes

OK so i have been working on a calculator with classes(To play with classes but a function) and when ever I run it all i get back is zero no matter what I type in or say to use for the operator. Here is my code:
Main class:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* #return the finial
*/
public static double getFinial() {
return finial;
}
/**
* #param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* #return the numof
*/
public static int getNumof() {
return numof;
}
/**
* #param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* #return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* #param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
#SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
here is the add class:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
I do have three more classes but it is just operator classes let me know if you need them
Just a quick look shows some significant basic issues. For example, in a basic setter, like:
public static void setFinial(double finial) {
finial = numof;
}
from your code, what you most likely intended was
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
If your static variable and your parameter have the same name, you can't access both. The compiler will think you're talking about the parameter. Also, be careful that your setter is using the parameter paramFinial instead of the probably unintentional reference to numof.
It would be a lot easier to read the rest of your code if you would comment what finial, numof, and your other variables represent.

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Categories

Resources